function a (){
this.testing = 'testing';
}
function b (){
}
b.prototype = new a();
console.log(b.testing);
The console shows undefined, rather than 'testing'. What am I doing wrong?
Prototypical inheritance allows us to reuse the properties or methods from one JavaScript object to another through a reference pointer function.
By now you must have realized the difference between classical inheritance and prototypal inheritance. Classical inheritance is limited to classes inheriting from other classes. However prototypal inheritance includes not only prototypes inheriting from other prototypes but also objects inheriting from prototypes.
Prototypal inheritance is a form of object-oriented code reuse. Javascript is one of the only [mainstream] object-oriented languages to use prototypal inheritance. Almost all other object-oriented languages are classical. In classical inheritance, the programmer writes a class, which defines an object.
We can use obj. __proto__ to access it (a historical getter/setter, there are other ways, to be covered soon). The object referenced by [[Prototype]] is called a “prototype”. If we want to read a property of obj or call a method, and it doesn't exist, then JavaScript tries to find it in the prototype.
You haven't made an instance of 'b' yet.
var bInstance = new b();
console.log(bInstance.testing);
In other words, the properties of the prototype only appear on objects of type b
, not on the b()
constructor function itself.
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