开发者

Deep inheritance with JavaScript?

开发者 https://www.devze.com 2023-01-05 15:14 出处:网络
I know that I could do a simple prototypal inheritance in JavaScript like this: var Parent = function() {

I know that I could do a simple prototypal inheritance in JavaScript like this:

var Parent = function() {
};

var Child = function() {
}

Child.prototype = new Parent();
Child.prototype.constructor = Child;

However, I'm curious to how one would accomplish deeper inheritances? What abo开发者_StackOverflow中文版ut multi-inheritance, is that possible?


You can't do multiple inheritance in JavaScript. You can do deeper inheritance by simply going further:

var Parent = function() {};
var Child = function() {};
var InnerChild = function() {};

And to show it works:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消