How exactly does !function(){}() work?
This question already has an answer here:
What the ! does
When you use !
, the function becomes the single operand of the unary (logical) NOT operator.
This forces the function to be evaluated as an expression, which allows it to be invoked immediately inline.
Other alternatives
You can do this with just about any operator. Here are some examples...
'invoke',function(){ /*code*/ }();
1+function(){ /*code*/ }();
void function(){ /*code*/ }();
~function(){ /*code*/ }();
+function(){ /*code*/ }();
Nice thing about some of these is that the meaning of the operator is not overloaded.
The problem with ()
When you use ()
around the function, you can hit some bugs that will crop up if you have more than one in a row without a semicolon separating them.
(function() {
alert('first');
}())
(function() {
alert('second');
}())
// TypeError: undefined is not a function
This will result in a TypeError
, because the pair of outer ()
around the second function will be interpreted as intending to call a function. The first one doesn't return a function of course, so you're trying to call on undefined
.
How using a different operator copes with (or avoids) the problem
Even an operator like +
, which is overloaded to some degree won't cause an error.
If you do this...
+function() {
alert('first');
}()
+function() {
alert('second');
}()
The first +
is interpreted as a unary + operator, and it converts the result returned from the first function, which in this case is undefined
so it gets converted to NaN
.
The second +
will be interpreted as the addition operator, and so will try to add NaN
to the return result of the second function, which again here is undefined
.
The result of course is NaN
, but it is harmless. There's no illegal code to throw an error.
Demonstration of how the operators interact with the functions
To prove this, just give each function a return value, then paste it into the console...
+function() {
alert('first');
return "10";
}()
+function() {
alert('second');
return 20;
}()
// 30
You'll get the two alert
s, and then the console will show 30
because the first +
operator converts the String "10"
to the Number 10
, and the second +
added the two results together.
The !
is an ordinary logical negation.
The ()
executes the function.
上一篇: Javascript中的功能是什么意思?
下一篇: function(){}()如何工作?