Javascript - why a function called at runtime is declared

Just declaring a function to an object causes it to be called

var a = {}; a.xyz = new function() { alert("dosomething"); } 

I would expect the declared a.xyz function a.xyz be called only when called:
 a.xyz(); 

What is wrong with my assumption?

+5
source share
3 answers

Delete a new one and everything will be fine:

 var a = {}; a.xyz = function() { alert("dosomething"); } 

JSFiddle: http://jsfiddle.net/vnj8pzm1/

EDIT: More on IIFE - Expression with immediate calling function (IIFE)

+3
source

When you put new in front of a function definition, your function is immediately called as a constructor.

As mentioned ridiculously, you should not have new before defragmenting the function. However, what is ridiculous mentioned in the comment is incorrect

new function () {} or new function () {} (); will call the function in the same way as function () {} (); or (function () {} ());

new function() {} will create a new instance of an anonymous type, so there is an object in your a.xyz code

if you change it to function(){}() , it will immediately execute this function and will return nothing. See http://jsfiddle.net/mendesjuan/kzhg9ggu/

+3
source

In short:

The new statement creates an instance of the object with a new one, and therefore it runs immediately after the declaration.

Not so short

 xyz= function(){}; 

Puts a link to an anonymous function in xyz and points to a function.

 xyz= new function(){}; 

Puts a link to a newly created instance of an anonymous constructor function, so it will point to an object. Try typeof new function(){} and you will get an object.

When the new function(){alert('foo');} code is executed, the following events occur:

  • A new object is created.
  • The constructor function is called with the specified arguments and is associated with the newly created object. If no argument list is specified, function () is called without arguments.
  • The object returned by the constructor function becomes the result of an entire new expression. If the constructor function does not explicitly return an object, the object created in step 1 is used instead.
+3
source

Source: https://habr.com/ru/post/1202531/


All Articles