Deep inheritance using JavaScript?

I know that I could do the simplest prototype inheritance in JavaScript as follows:

var Parent = function() {
};

var Child = function() {
}

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

However, I am curious how to achieve deeper inheritance? What about multi-inheritance?

+3
source share
1 answer

You cannot do multiple inheritance in JavaScript. You can do deeper inheritance just by going further:

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

And to show that 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
+6
source

Source: https://habr.com/ru/post/1752674/


All Articles