使用JavaScript进行深度继承?

Tow*_*wer 3 javascript oop inheritance

我知道我可以在JavaScript中做一个简单的原型继承,如下所示:

var Parent = function() {
};

var Child = function() {
}

Child.prototype = new Parent();
Child.prototype.constructor = Child;
Run Code Online (Sandbox Code Playgroud)

但是,我很想知道如何实现更深层次的遗产?那么多继承怎么可能呢?

Cla*_*diu 6

您不能在JavaScript中进行多重继承.只需更进一步,您就可以做更深的继承:

var Parent = function() {};
var Child = function() {};
var InnerChild = function() {};
Run Code Online (Sandbox Code Playgroud)

并表明它的工作原理:

Parent.prototype.x = 100;
Child.prototype = new Parent();
Child.prototype.y = 200;   
InnerChild.prototype = new Child();
InnerChild.prototype.z = 300;

var ic = new InnerChild();
console.log(ic.x); //prints 100, from Parent
console.log(ic.y); //prints 200, from Child
console.log(ic.z); //prints 300, from InnerChild, who only wants to express itself
Run Code Online (Sandbox Code Playgroud)