Javascript anonymous function call
This question already has an answer here:
When the keyword function
is met in a statement position (as the first token in a statement), the function declaration is expressed as a function statement. Function statements are hoisted to the top of the scope, cannot be immediately invoked and must have a name.
When the keyword is met in an expression position (ie not as the first token in a statement, in your example !
is the first token), the function declaration is expressed as a function expression, which may be anonymous and returns the value of the newly created function. Since it returns the value of the newly created function, you may immediately invoke it by adding parenthesis after it.
Wrapping the declaration inside parenthesis does the same but is more common than prefixing it with a !
or +
:
(function () {
...
}());
The second form function () {}
is a statement. The !
operator converts this into an expression. You will also find cases where people use -
or +
before the function
keyword.
When you have an expression evaluating to a function, you can call that function by using the ()
operator.
Another (perhaps easier to understand) way to achieve the save same effect is with another set of parenthesis:
( function(x) { body; } )(arg);
By placing the function inside the parenthesis, you again convert it to an expression, which evaluates to a function. This function is called with arg
as an argument.
As far as the exclamation mark goes, that is not magic. It converts the result to a true/false.
Your problem may be that your anonymous function has an error inside it.
链接地址: http://www.djcxy.com/p/17418.html上一篇: function(){}()如何工作?
下一篇: Javascript匿名函数调用