1

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

Prule
  • 13
  • 3

1 Answers1

4

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Aarg… I tried something similar before but used `ClassName` accidentally. Updated fiddle: http://jsfiddle.net/fcaQ9/1/ Using `this.constructor.prototype.do.call(this)` as mentioned [here](http://stackoverflow.com/a/18617418) is not a solution, is it? – Prule Jul 31 '14 at 14:05
  • 2
    [No, it's not](http://stackoverflow.com/a/16105890/1048572) - imagine your `Class` does not overwrite `SuperClass::do`, you'll get infinite recursion similar to [this example](http://stackoverflow.com/a/24700014/1048572) – Bergi Jul 31 '14 at 14:14
  • Thank you for the references. – Prule Jul 31 '14 at 14:24