我知道在JavaScript中可以通过以下方式进行简单的原型继承:
var Parent = function() {
};
var Child = function() {
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
不过,我很好奇如何实现更深层次的继承?多重继承是否也可以实现?
我知道在JavaScript中可以通过以下方式进行简单的原型继承:
var Parent = function() {
};
var Child = function() {
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
不过,我很好奇如何实现更深层次的继承?多重继承是否也可以实现?
在JavaScript中,您无法进行多重继承。但是,您可以通过简单地进一步深入来实现更深层次的继承:
var Parent = function() {};
var Child = function() {};
var InnerChild = function() {};
并且为了展示它的工作原理:
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