Prototype chain: call “super” method over multiple levels

别来无恙 提交于 2019-11-27 08:37:08

问题


I have got the following prototype chain

  • SuperSuperClass
    • SuperClass
      • Class

each with a method named do.

What is the common approach for calling the respective super class method?
For the moment I use <ClassName>.prototype.__proto__.<methodName>.call(this) but that looks odd.

Using the following code the console prints (as expected):

  • Class.prototype.do
  • SuperClass.prototype.do
  • SuperSuperClass.prototype.do
SuperSuperClass = function SuperSuperClass() {}
SuperSuperClass.prototype.do = function() {
    console.log('SuperSuperClass.prototype.do');
};

function SuperClass() {
    SuperSuperClass.call(this);
}
SuperClass.prototype = Object.create(SuperSuperClass.prototype);
SuperClass.prototype.constructor = SuperClass;
SuperClass.prototype.do = function() {
    console.log('SuperClass.prototype.do');
    SuperClass.prototype.__proto__.do.call(this);
};

function Class() {
    SuperClass.call(this);
}
Class.prototype = Object.create(SuperClass.prototype);
Class.prototype.constructor = Class;
Class.prototype.do = function() {
    console.log('Class.prototype.do');
    Class.prototype.__proto__.do.call(this);
};

var objClass = new Class();
objClass.do();

JSFiddle


回答1:


What is the common approach for calling the respective super class method?

Use <SuperClassName>.prototype.<methodName>.call(this). It's not only shorter, but also has the benefit of working in environments that don't support the non-standard __proto__ property.



来源:https://stackoverflow.com/questions/25060621/prototype-chain-call-super-method-over-multiple-levels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!