Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prototype property throwing undefined [duplicate]

Tags:

javascript

oop

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

like image 464
Shane Avatar asked Mar 17 '23 18:03

Shane


1 Answers

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
like image 61
dfsq Avatar answered Apr 02 '23 00:04

dfsq