Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding inherited prototype method and calling the original one inside the new one

In the following piece of code, how can I access the A.prototype.log inside of B.prototype.log?

function A() {}

A.prototype.log = function () {
    console.log("A");
};

function B() {}

B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;

B.prototype.log = function () {
    //call A.prototype.log here
    console.log("B");
};

var b = new B();
b.log();

I know I could just write A.prototype.log.call(this) but I thought maybe there is a more elegant way, that lets me call it in a relative way, like "call the method 'log' of the next higher instance in the prototype chain". Is something like this possible?

like image 241
basilikum Avatar asked Jul 25 '13 12:07

basilikum


People also ask

Can we override prototype in JavaScript?

Prototyping allows objects to inherit, override, and extend functionality provided by other objects in a similar manner as inheritance, overriding, abstraction, and related technologies do in C#, Java, and other languages. Every object you create in JavaScript has a prototype property by default that can be accessed.

Is prototype the same as inheritance?

The object from where the properties are inherited is called the prototype. In short, objects can inherit properties from other objects — the prototypes.

What is the difference between __ proto __ and prototype?

The prototype property is set to function when it is declared. All the functions have a prototype property. proto property that is set to an object when it is created using a new keyword. All objects behavior newly created have proto properties.

How does prototypical inheritance work?

The Prototypal Inheritance is a feature in javascript used to add methods and properties in objects. It is a method by which an object can inherit the properties and methods of another object. Traditionally, in order to get and set the [[Prototype]] of an object, we use Object. getPrototypeOf and Object.


1 Answers

You could use Object.getPrototypeOf

...
B.prototype.log = function () {
    Object.getPrototypeOf (B.prototype).log.call(this)
    console.log("B");
};
...
b.log(); //A B

Note: Object.getPrototypeOf is ECMASript 5, see the compatibility


There is also the non standard and deprecated __proto__ property (compatibility) which

references the same object as its internal [[Prototype]]

and would allow you to call your As' log method like this

B.prototype.__proto__.log.call(this)

But

the preferred method is to use Object.getPrototypeOf.

like image 85
Moritz Roessler Avatar answered Sep 27 '22 22:09

Moritz Roessler