Saturday 30 March 2013

anonymous-function

This answer is not strictly related to the question, but you might be interested to find out that this kind of syntax feature is not particular to functions. For example, we can always do something like this:
alert(
    {foo: "I am foo", bar: "I am bar"}.foo
); // alerts "I am foo"
Related to functions. As they are objects, which inherit from Function.prototype, we can do things like:
Function.prototype.foo = function () {
    return function () {
        alert("foo");
    };
};

var bar = (function () {}).foo();

bar(); // alerts foo



One thing I found confusing is that the "()" are grouping operators.
Here is your basic declared function.
Ex. 1:
var message = 'SO';

function foo(msg) {
    alert(msg);
}

foo(message);
Functions are objects, and can be grouped. So let's throw parens around the function.
Ex. 2:
var message = 'SO';

function foo(msg) {  //declares foo
    alert(msg);
}

(foo)(message);     // calls foo
Now instead of declaring and right-away calling the same function, we can use basic substitution to declare it as we call it.
Ex. 3.
var message = 'SO';

(function foo(msg) {
    alert(msg);
})(message);          // declares & calls foo
Finally, we don't have a need for that extra foo because we're not using the name to call it! Functions can be anonymous.
Ex. 4.
var message = 'SO';

(function (msg) {   // remove unnecessary reference to foo
    alert(msg);
})(message);
To answer your question, refer back to Example 2. Your first line declares some nameless function and groups it, but does not call it. The second line groups a string. Both do nothing. (Vincent's first example.)
(function (msg){alert(msg)});  
('SO');                       // nothing.

(foo); 
(msg); //Still nothing.
But
(foo)
(msg); //works



http://stackoverflow.com/questions/1140089/how-does-an-anonymous-function-in-javascript-work






No comments:

Post a Comment