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?
Immediately invoked function expressions can be used to avoid variable hoisting from within blocks, protect against polluting the global environment and simultaneously allow public access to methods while retaining privacy for variables defined within the function.
An Immediately-invoked Function Expression (IIFE for friends) is a way to execute functions immediately, as soon as they are created. IIFEs are very useful because they don't pollute the global object, and they are a simple way to isolate variables declarations.
In interpreted languages, the code is run from top to bottom and the result of running the code is immediately returned. You don't have to transform the code into a different form before the browser runs it.
This is called IIFE (Immediately Invoked Function Expression). One of the famous JavaScript design patterns, it is the heart and soul of the modern day Module pattern. As the name suggests it executes immediately after it is created.
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)
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With