I've recently been looking into what the new operator does when, particularly when used for creating a function. I've been playing around/testing what is returned from different function instantiation. Could you guys clear up a few questions I have regarding function instantiation:
I understand that you can create a function by doing either using the function keyword:
new function() { *statements*}
or by calling the function constructor:
new Function(*arg1, functionBodyString*);
I understand that using the new operator calls upon the function (constructor) to create a function (a function object). But I can also see that the function keyword is used as if it's creating an actual function in the same sense as other languages.
- Is the function keyword just syntax sugar for creating functions allowing you to declare the function body after the function creation, rather than passing in a set of statements as a string like you would with the Function contructor?
- When creating a function, does the Function() constructor call upon it's function body during its construction? I would assume so because creating a function this way has its inner functions available to it.
- What is the difference between function() and new function()? I've read there's no difference on here but the difference is that using the new operator makes all of its inner functions available (hence question 2) but not using it requires you to call upon that function for it's inner properties to instantiate. What's going on there?
Thanks! :)
P.S
To clear up question 2:
When I do
new function(){ this.myFunction = function(){ ... }}
the function 'myFunction' is available. But when I do
function(){ this.myFunction = function(){ ... }}
the function 'myFunction' is not available. Why is this? Is it because the new function/constructor executes the functions body? What is the new operator doing here to support this?