Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

javascript - [[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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...