inherit prototype methods from other classes without overriding own prototype methods

断了今生、忘了曾经 提交于 2019-12-25 12:51:20

问题


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 ParentConstructor = function(){
};

ParentConstructor.prototype = {
    test: function () {
        console.log("Child");
    }
};

var ChildConstructor = function(){
    ParentConstructor.call(this)
};

ChildConstructor.prototype = {

    test2: "child proto"
};

var TempConstructor = function(){};
TempConstructor.prototype = ParentConstructor.prototype;
ChildConstructor.prototype = new TempConstructor();
ChildConstructor.prototype.constructor = ChildConstructor;



var child = new ChildConstructor();

child.test();
console.log(child.test2)

console.log(child, new ParentConstructor());

Which isn't working, because I lose my test2 prototype method / property when I add the inheritance from my ParentConstructor.

I've tried other ways to extend the prototype methods of a class with some prototype props form other classes but I have failed each time, because I couldn't find a way not to override the previous methods each time.

I have also tried the var Child = Object.create(Parent.Prototype), but when I define new props I lose the parent props.


回答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";



回答2:


The best example I can think of comes from:

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

function Being() {
    this.living = true;
    this.breathes = function () {
       return true;
    };
}

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

Robert.prototype = new Being(); 

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

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.



来源:https://stackoverflow.com/questions/18217831/inherit-prototype-methods-from-other-classes-without-overriding-own-prototype-me

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!