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?
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.
The object from where the properties are inherited is called the prototype. In short, objects can inherit properties from other objects — the prototypes.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With