Thursday 25 May 2017

javascript - Why do you need to invoke an anonymous function on the same line?

Drop the semicolon after the function definition.




(function (msg){alert(msg)})
('SO');


Above should work.



DEMO Page: https://jsfiddle.net/e7ooeq6m/



I have discussed this kind of pattern in this post:




jQuery and $ questions



EDIT:



If you look at ECMA script specification, there are 3 ways you can define a function. (Page 98, Section 13 Function Definition)



1. Using Function constructor



var sum = new Function('a','b', 'return a + b;');
alert(sum(10, 20)); //alerts 30



2. Using Function declaration.



function sum(a, b)
{
return a + b;
}

alert(sum(10, 10)); //Alerts 20;



3. Function Expression



var sum = function(a, b) { return a + b; }

alert(sum(5, 5)); // alerts 10


So you may ask, what's the difference between declaration and expression?




From ECMA Script specification:




FunctionDeclaration :
function Identifier ( FormalParameterListopt ){ FunctionBody
}



FunctionExpression :
function Identifieropt ( FormalParameterListopt ){ FunctionBody

}




If you notice, 'identifier' is optional for function expression. And when you don't give an identifier, you create an anonymous function. It doesn't mean that you can't specify an identifier.



This means following is valid.



var sum = function mySum(a, b) { return a + b; }



Important point to note is that you can use 'mySum' only inside the mySum function body, not outside. See following example:



var test1 = function test2() { alert(typeof test2); }

alert(typeof(test2)); //alerts 'undefined', surprise!

test1(); //alerts 'function' because test2 is a function.


Live Demo




Compare this to



 function test1() { alert(typeof test1) };

alert(typeof test1); //alerts 'function'

test1(); //alerts 'function'






Armed with this knowledge, let's try to analyze your code.



When you have code like,



    function(msg) { alert(msg); }


You created a function expression. And you can execute this function expression by wrapping it inside parenthesis.




    (function(msg) { alert(msg); })('SO'); //alerts SO.

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...