Search code examples
javascriptprototype

Override function in JavaScript


Possible Duplicate:
Calling base method using JavaScript prototype

I want to inheritance object that will override function in javascript.

From the method I want to call to the base method. In this case I inherit object reader from Person and now I want to override the function getName meaning that in reader first I want to call the function on Person and then to do some changes.

<script>
    /* Class Person. */
    function Person(name) {
        this.name = name;
    }
    Person.prototype.getName = function() {
        return this.name;
    }

    var reader = new Person('John Smith');
    reader.getName = function() {
        // call to base function of Person, is it possible?
        return('Hello reader');
    }
    alert(reader.getName());
</script>

Solution

  • Since you are correctly overriding the function on the object itself and not on its prototype, you can still call the prototype function with your object.

    reader.getName = function() {
        var baseName = Person.prototype.getName.call(this);
        ...
    }