Reputation: 2844
The mere declaration of a function to an object leads to its invocation
var a = {};
a.xyz = new function() {
alert("dosomething");
}
a.xyz
only gets invoked when I call it:
a.xyz();
What is wrong with my assumption?
Upvotes: 5
Views: 103
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
Reputation: 17471
The new operator create an instance of the object with new, and that's why is executed right after the declaration.
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:
Upvotes: 3
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