There are two classes api and max is one that I want to inherit from them route .

 function api () { this.run = function () { console.log('run'); } } function max() { this.sub = function () { console.log('sub'); } } function route() { // some... } route.prototype = new api(); route.prototype = new max(); var r = new route(); r.run(); r.sub(); 

I get an error, how do I make the parent method call work? At the same time, it is necessary that the method be called as r.run(); or r.sub();

  • Actually, it is about multiple inheritance . - Dmitriy Simushev

1 answer 1

Multiple inheritance in js is not provided.

But if you really want to imitate him, then you need to select one of the parent classes and use it as a basis for the new, and from the second just drag and drop methods.

I draw your attention that the connection with the prototype of the second class is lost, that is, the dynamic addition of methods to it will not affect the heir. However, I do not consider this a problem.

By the way, if you really want to keep the dynamic link, then in ES6 there is an opportunity to use Proxy , in which you decide how to access the property. But this is already from the field of crutches, moreover, with dubious support.

 function First(x) { this.x = x; } First.prototype.someMethod = function () { console.log('someMethod from First'); }; function Second(y) { this.y = y; } Second.prototype.doSmth = function () { console.log('doSmth from Second'); }; function Both(x, y) { First.call(this, x); Second.call(this, y); } Both.prototype = Object.create(First.prototype) for (var key in Second.prototype) { Both.prototype[key] = Second.prototype[key]; } var obj = new Both(3, 4); obj.someMethod(); obj.doSmth(); console.log(obj.x, obj.y);