what does !function in Javascript mean?
This question already has an answer here:
It is short-hand or alternative of self-invoking anonymous function:
(function(){
// code
})();
Can be written:
!function(){
// code
}();
You can also use +
instead of !
.
If you simply did:
function(){
// code
}();
That will create problems, that's why you need to add !
before it which turns the function declaration into function expression .
Quoting docs, section 12.4:
An ExpressionStatement cannot start with the function keyword because that might make it ambiguous with a FunctionDeclaration.
To better understand the concept, you should check out:
they're negating the result, not the function itself:
!function( x ){ return x }( true );
!true
false
In reality, it's a slightly compressed form of:
(function(){}())
since it requires 1 less character. The reason it's needed is that you can't call a function declaration directly, eg this is invalid:
function(){}()
but adding the !
at the beginning turns it into a function expression
and makes it work.
It's usually used to work around a quirk in the JavaScript syntax. This gives a syntax error:
function() {
}();
It's read as a function declaration (like function foo () {}
), rather than a function expression. So adding the ! before it, or wrapping it in parentheses, forces the parser to understand that it's an expression.
下一篇: Javascript中的功能是什么意思?