Function Returning A Function To A Variable. Why Does It Need The Extra Set Of ()?
Solution 1:
You use these parentheses all the time:
alert('foo');
Here, the parentheses call the function alert and pass in the argument 'foo'.
Take this function for example:
function test() {
alert('foo');
}
Running test will only give you a reference to the function. test() will take that reference and call it.
In your specific example, this is precisely what is happening:
var varFuncTest = (function(){
_funcTest = function(params){
return"These are the params that were passed in: " + params;
};
return _funcTest;
})();
function() {...} returns another function (_funcTest). Those parentheses at the end call that returned function. If you omit them, varFuncTest will store a function. If you keep them, varFuncTest will store the output of that function instead.
Just to illustrate this, execute your second chunk of code and then run this:
varFuncTest();
You should get the same output as the first code chunk.
Solution 2:
Javacript has the concept of an immediately invoked function. This is a function that is called as soon as it is defined. These need to be function expressions instead of function statements.
var a = function() {return"hi"}; // A reference to a function.. to call later.
alert(a()); // Call the function now.vs
var a = (function() {return"hi"}()); // Call the function, return the value in one stop.// a now has the result of the function.alert(a);
Many of the answers given are true, or true-ish, but there is another aspect that none of them have mentioned.
When doing an assignment, such as
var a = (function() {}());
The outer-most level of parens are NOT needed by the compiler, but they server to inform the human reading the code that a immediately-invoked function is in place.
On the other hand, code like
(function() {}()); // One style
(function() {})(); // Another stylethe parens are needed to force the compiler to read an expression, and thus a function-expression, rather than a function statement.
Using almost any other operator in front of the function keyword works, such as:
!function() {}(); // Another styleWhile that works, it isn't the normal 'idiom' to-to-say of Javascript.
TL-DR: The parens are there more the sake of humans than computers.
BTW: Please stick with the standard coding conventions. There are a lot of non-standard-but-legal things you can do. Don't. It confuses the person who comes after you.
Post a Comment for "Function Returning A Function To A Variable. Why Does It Need The Extra Set Of ()?"