Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);     ​ 
like image 644
hrishikeshp19 Avatar asked May 11 '12 19:05

hrishikeshp19


People also ask

What is the difference between function and function in JavaScript?

function is a language keyword used to define functions. Function is the builtin prototype object that represents all functions.

What is the new function in JavaScript?

When a function is called with the new keyword, the function will be used as a constructor. new will do the following things: Creates a blank, plain JavaScript object. For convenience, let's call it newInstance .

What are the 3 types of functions in JavaScript?

There are 3 ways of writing a function in JavaScript: Function Declaration. Function Expression. Arrow Function.

What is new function?

The major difference from other ways we've seen is that the function is created literally from a string, that is passed at run time. All previous declarations required us, programmers, to write the function code in the script. But new Function allows to turn any string into a function.


1 Answers

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 
like image 133
Joseph Avatar answered Sep 22 '22 03:09

Joseph