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
985 views
in Technique[技术] by (71.8m points)

new operator - JavaScript difference between function and new function

The following JavaScript code is very confusing to me. Could anyone help me understand. Why does PersonY not have prototype property.

PersonX = function(){};
PersonY = new function(){};
alert(PersonX.prototype);
alert(PersonY.prototype);    
?
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
PersonX = function(){};

Places a reference to an anonymous function into PersonX. PersonX points to a function.

PersonY = new function(){};

Places a reference to a newly constructed instance of an anonymous constructor function into PersonY. PersonY points to an object.


Regarding the prototype, PersonY has one. However, since there were no properties and methods attached to the constructor before nor after instantiation, it has a blank prototype*.

You can actually check PersonY's prototype by doing console.log(PersonY). You will see that it has a prototype property (I see it as __proto__ in Chrome) which is "blank". But it has 2 hidden properties, constructor which is the constructor function that made the object, and another __proto__ which leads you to the next "chain link" which would be the Object object.

*Not really blank since prototype is a chain. This prototype level may be blank, but the next higher prototype may have, or in this case, does have properties and methods.

Object prototype -> Constructor prototype -> Your Instance will have:
- toString()        - blank                  - toString()
- hasOwnProperty()                           - hasOwnProperty()
- and more...                                - and more...
                                             - ...but nothing from Constructor

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

...