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
31
|
One thing I found confusing is that the "()" are grouping operators.
Here is your basic declared function.
Ex. 1:
Functions are objects, and can be grouped. So let's throw parens around the function.
Ex. 2:
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.
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.
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.)
But
|
http://stackoverflow.com/questions/1140089/how-does-an-anonymous-function-in-javascript-work
No comments:
Post a Comment