Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep inheritance with JavaScript?

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 about multi-inheritance, is that possible?

like image 237
Tower Avatar asked Jun 11 '26 23:06

Tower


1 Answers

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
like image 54
Claudiu Avatar answered Jun 13 '26 17:06

Claudiu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!