inherit prototype methods from other classes witho

2019-09-05 21:31发布

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.

2条回答
【Aperson】
2楼-- · 2019-09-05 21:47

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";
查看更多
Bombasti
3楼-- · 2019-09-05 21:55

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.

查看更多
登录 后发表回答