Is there something wrong with this approach to calling super () in javascript?

I was working on a project and decided that the best way to implement the functionality I wanted was to override the method. At that time I did not understand that javascript had no idea just to call super (), so I started to do some research.

I found an article ( http://blog.salsify.com/engineering/super-methods-in-javascript ) that describes several methods for calling super methods.

I would not be very pleased with any of these options, although I came up with the following. Also available on the fiddle https://jsfiddle.net/fpgm8j9n/ .

var Food = function( name ){
    this.name = name;
}

Food.prototype.sayName = function(){
    console.log( 'I am a ' + this.name );
}

var Fruit = function( name, color ){
    Food.call( this, name );
    this.color = color;

    this.super = Object.getPrototypeOf( Object.getPrototypeOf( this ) );
}

Fruit.prototype = Object.create( Food.prototype );

Fruit.prototype.sayName = function(){
    console.log( 'I am a fruit and I am the color ' + this.color );
}

var orange = new Fruit( 'apple', 'red' );

// runs the overridden method in orange
orange.sayName(); // I am a fruit and I am the color red

// runs the super method
orange.super.sayName.call( orange ); // I am a apple

I. ? - , , -, ? javascript .

var Child = Parent.extend({
  // ...
  doSomething: function(x, y) {
    this.doSomethingElse(x);
    return Parent.prototype.doSomething.call(this, x, y);
  }
});
+4
1

super , ( ). , :

Fruit.prototype.sayName = function(){
    this.super.sayName.call(this);                 // prints "I am a apple"
    console.log( 'I am the color ' + this.color ); // prints "I am the color red"
}

var orange = new Fruit( 'apple', 'red' );
orange.sayName();

( orange.super.sayName.call( orange ); , , -OO-. , . - (, ), , .

super , , . , :

var Grape = function(variety) {
    Fruit.call(this, "grape", "purple");
    this.variety = variety;
};

Grape.prototype = Object.create(Fruit.prototype);

Grape.prototype.sayName = function() {
    this.super.sayName.call(this);
    console.log('I am a ' + this.variety + ' grape');
};

var concordGrape = new Grape("Concord");
concordGrape.sayName(); // unbounded recursion / causes stack overflow

, this.super , :

this                                               // Grape object
Object.getPrototypeOf(this)                        // Grape.prototype
Object.getPrototypeOf(Object.getPrototypeOf(this)) // Fruit.prototype

, Grape.prototype.sayName this.super.sayName, Fruit.prototype.sayName, . Fruit.prototype.sayName this.super.sayName, , , .

super :

var Grape = function(variety) {
    Fruit.call(this, "grape", "purple");
    this.variety = variety;
    this.super = Object.getPrototypeOf( Object.getPrototypeOf( this ) );
};

this , , .

, super , ( ). , , .

+6

All Articles