Lokomotywa
Lokomotywa

Reputation: 2844

javascript - why is declared function invoked at runtime

The mere declaration of a function to an object leads to its invocation

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

I would expect, that the declared function a.xyz only gets invoked when I call it:

a.xyz();

What is wrong with my assumption?

Upvotes: 5

Views: 103

Answers (3)

Hristo Enev
Hristo Enev

Reputation: 2541

Remove new and everything will be fine:

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

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

EDIT: More about IIFE - Immediately-Invoked Function Expression (IIFE)

Upvotes: 3

Tomas Ramirez Sarduy
Tomas Ramirez Sarduy

Reputation: 17471

In short:

The new operator create an instance of the object with new, and that's why is executed right after the declaration.

In not so short

xyz= function(){};

Places a reference to an anonymous function into xyz and points to a function.

xyz= new function(){};

Places a reference to a newly constructed instance of an anonymous constructor function, so it will points to an object. Try typeof new function(){} and you will get object.

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

  1. A new object is created
  2. The constructor function is called with the specified arguments and this bound to the newly created object. If no argument list is specified, function() is called without arguments.
  3. The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead.

Upvotes: 3

Ruan Mendes
Ruan Mendes

Reputation: 92294

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

As iceless mentioned, you should not have new in front of your function defintion. However, what iceless mentioned in the comment is incorrect

new function() {} or new function() {}(); will invoke the function just like function() {}(); or (function() {}());

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

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

Upvotes: 3

Related Questions