Skip to content Skip to sidebar Skip to footer

Inherit Prototype Methods From Other Classes Without Overriding Own Prototype Methods

Is there a better way of having a class inherit prototype methods from another class and still be able to define new prototype methods on the class that inherits than this: var Par

Solution 1:

Setting up inheritance should take place before you define new properties on the prototype of ChildConstructor. And when you define new prototype properties, you also shouldn't override the whole prototype property. Instead, you can simply add new properties, like you already did with the constructor property:

ChildConstructor.prototype = new ParentConstructor();ChildConstructor.prototype.constructor = ChildConstructor;ChildConstructor.prototype.test2 = "child proto";

Solution 2:

The best example I can think of comes from:

http://robertnyman.com/2008/10/06/javascript-inheritance-how-and-why/

functionBeing() {
    this.living = true;
    this.breathes = function () {
       returntrue;
    };
}

functionRobert() {
    // Robert.prototype = new Being(); /* edit */this.blogs = true;
    this.getsBored = function () {
        return"You betcha";
    };
}

Robert.prototype = newBeing(); 

Robert.prototype.newMethod = function() {
    console.log('new method executed');
    returnthis;
}

Note this example, has been updated, the first comment below is directed at the first code I had up, which contained the prototype inside the Robert method.

Post a Comment for "Inherit Prototype Methods From Other Classes Without Overriding Own Prototype Methods"