why is the prototype property
of the instance
throwing undefined
?.
function Test(name){
this.name = name;
}
Test.prototype = {
constructor: Test,
sayHello : function(){
console.log(this.name);
}
}
var z = new Test("Hello");
console.log(z.prototype); //undefined
console.log(zUtils.constructor); // Test
I am able to access the sayHello method via z.sayHello(
), then why is my instance
prototype
returning me undefined instead of Test.prototype
?.
The problem of confusion is that the word prototype
kind of has two meanings.
1. Function property. Any function can have a prototype
property, which is an object. In your case
Test.prototype = {
sayHello: function() {}
}
Properties of this object become inherited properties and methods of the objects constructed with this constructor function:
var z = new Test();
Now z
has a method property sayHello
, which you configured with the help of the Test.prototype
object.
2. Instance prototype. The instance object, in your case z
, has internal reference to the prototype object from point #1 above. This reference is used internally to resolve properties and methods in the prototype chain. However this reference is not supposed to be accessible directly, and you can't access this reference with prototype
property of the instance.
In chrome and Firefox you can use __proto__
property, but its usage is deprecated.
To get a prototype which was used during object construction you should use Object.getPrototypeOf
:
Object.getPrototypeOf(z) === Test.prototype; // true
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