Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[[Prototype]] vs prototype: ..what is the difference? (MyCons.__proto__ === MyCons.prototype) equals FALSE

It seems like there is a difference here...

Let's say we have function MyConstructor() {}

MyConstructor's [[Prototype]] is Function.prototype, not MyConstructor.prototype.

In other (non-standard/"console.log-able") words:
MyConstructor.__ proto__ is not MyConstructor's MyConstructor.prototype

TRY THIS:

function MyConstructor() {};
(MyConstructor.__proto__ === MyConstructor.prototype); //false?! why?

Why is this so? Can someone explain it to me the difference?

like image 901
Jan Carlo Viray Avatar asked Feb 26 '12 09:02

Jan Carlo Viray


1 Answers

Think of it like this. MyConstructor is a function object, so it was created by Function; therefore its [[Prototype]] (or __proto__) is identical to Function.prototype.

In the same way, var myObj = new MyConstructor() creates an object myObj with a [[Prototype]] identical to MyConstructor.prototype.

To put it another way, functions have a prototype property, and when you invoke functions with new, they will construct an object having a [[Prototype]] identical to the constructor function's prototype property... however a function's prototype property is not the same thing as its [[Prototype]] (or __proto__) property, because a function follows the same rules as other objects and gets its internal [[Prototype]] property from the function that constructed it (which is always Function, incidentally).


To explain further, [[Prototype]] and prototype have entirely different purposes. [[Prototype]] is used when resolving an object's properties. If an object doesn't have a property, its [[Prototype]] is checked, and then that object's [[Prototype]], and so on, until either a property is found or you hit the end of the prototype chain.

In contrast, prototype is the mechanism by which you assign [[Prototype]] properties to objects, since you can't access them directly other than with the non-standard __proto__ property.

Since functions are objects, they have both a [[Prototype]] internal property, used to resolve properties as with normal objects, and a prototype property, which is assigned as the [[Prototype]] of new objects constructed by the function.

like image 152
Dagg Nabbit Avatar answered Oct 25 '22 02:10

Dagg Nabbit