Overriding the inherited prototype method and calling the original in the new

In the following code snippet, how can I access A.prototype.log inside 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 that I can just write A.prototype.log.call(this) , but I thought there might be a more elegant way that allows me to call it a relative way, like calling the log method of the next higher instance in the prototype chain. " Is this possible?

+6
source share
1 answer

You can use Object.getPrototypeOf

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

Note. Object.getPrototypeOf is ECMASript 5, see compatibility


There is also a non-standard and deprecated __proto__ property ( compatibility ), which

refers to the same object as its internal [[Prototype]]

and let you call your log method A s like this

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

But

the preferred method is to use Object.getPrototypeOf.

+5
source

Source: https://habr.com/ru/post/950267/


All Articles