Override function in JavaScript [duplicate]

Vincent answered your direct question but here is what you would do if you would like to set up a true inheritance hierarchy where you can further extend Reader.

Create your person class:

function Person(name) {
    this.name = name;
}

Person.prototype.getName = function(){
    alert('Person getName called for ' + this.name);
    return this.name;
}

Create a Reader class as well:

function Reader(name) {
    // Calls the person constructor with `this` as its context
    Person.call(this, name);
}

// Make our prototype from Person.prototype so we inherit Person's methods
Reader.prototype = Object.create(Person.prototype);

// Override Persons's getName
Reader.prototype.getName = function() {
    alert('READER getName called for ' + this.name);
    // Call the original version of getName that we overrode.
    Person.prototype.getName.call(this);
    return 'Something';
}
Reader.prototype.constructor = Reader;

And now we can repeat a similar process to extend Reader with say a VoraciousReader:

function VoraciousReader(name) {
    // Call the Reader constructor which will then call the Person constructor
    Reader.call(this, name);
}

// Inherit Reader's methods (which will also inherit Person's methods)
VoraciousReader.prototype = Object.create(Reader.prototype);
VoraciousReader.prototype.constructor = VoraciousReader;
 // define our own methods for VoraciousReader
//VoraciousReader.prototype.someMethod = ... etc.

fiddle:
http://jsfiddle.net/7BJNA/1/

Object.create: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/create

Object.create(arg) is creating a new object whose prototype is what was passed in as an argument.

Edit
Its been years since this original answer and now Javascript supports the class keyword which works as you’d expect if you’re coming from language like Java or C++. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

Leave a Comment