4

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?.

Shane
  • 5,517
  • 15
  • 49
  • 79
  • 3
    Because you can't get prototype of the object like this, there is no such property, because prototype is not exposed as a property. You can get it using `Object.getPrototypeOf` method. For example: `Object.getPrototypeOf(z) === Test.prototype`. – dfsq Dec 01 '14 at 12:14
  • 1
    @dfsq You shouldn't answer in comments. – Madara's Ghost Dec 01 '14 at 12:21

3 Answers3

5

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
dfsq
  • 191,768
  • 25
  • 236
  • 258
2

In order to get prototype, use Object.getPrototypeOf(). So, in your example, try with Object.getPrototypeOf(z)

Salil Dabholkar
  • 622
  • 3
  • 7
0

you should be using getPrototypeOf method on the object.like this:

Object.getPrototypeOf(z);

you can do like this:

Test.prototype=Object.getPrototypeOf(z);
    console.log(Test.prototype);
    console.log(Object.getPrototypeOf(z));
Suchit kumar
  • 11,809
  • 3
  • 22
  • 44