Reputation: 10528
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?
Upvotes: 6
Views: 2843
Reputation: 8611
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 A
s' log method like this
B.prototype.__proto__.log.call(this)
But
the preferred method is to use Object.getPrototypeOf.
Upvotes: 6