Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are so many ways to implement a <code>super</code> feature in JavaScript. For instance:</p> <pre><code>function SuperClass(someValue) { this.someValue = someValue; } SuperClass.prototype.method1 = function () { return this.someValue; }; function SubClass(someValue) { //call the SuperClass constructor this.super.constructor.call(this, someValue); } //inherit from SuperClass SubClass.prototype = Object.create(SuperClass.prototype); //create the super member that points to the SuperClass prototype SubClass.prototype.super = SuperClass.prototype; SubClass.prototype.method2 = function () { alert(this.super.method1.call(this)); }; var sub = new SubClass('some value'); sub.method2(); </code></pre> <p>EDIT:</p> <p>Here's an example of an extremely generic <code>super</code> method that relies on non-standard features. <strong>I really do not recommend this and it's just there as learning purposes.</strong></p> <pre><code>Object.prototype.super = function () { var superProto = Object.getPrototypeOf(Object.getPrototypeOf(this)), fnName = arguments.callee.caller.name, constructorName = this.constructor.name; if (superProto == null) throw constructorName + " doesn't have a superclass"; if (typeof superProto[fnName] !== 'function') { throw constructorName + "'s superclass (" + superProto.constructor.name + ") doesn't have a " + fnName + ' function'; } return superProto[arguments.callee.caller.name].apply( this, [].slice.call(arguments, 1) ); }; function A() { } A.prototype.toString = function toString() { //call super method Object.prototype.toString return this.super(); }; var a = new A(); console.log(a.toString()); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload