# 功能前的感叹号有什么作用？

2020/09/17 21:01 · javascript ·  · 0评论
``!function () {}();``

JavaScript语法101。这是一个函数声明

``function foo() {}``

`!`单独不会调用函数，当然，但我们现在可以把`()`结尾：`!function foo() {}()`它的优先级高于`!`并立即调用函数。

``(function(){})();``

``function () {}``

``function () {}()``

`!`在函数之前使用运算符会使它被视为表达式，因此我们可以调用它：

``!function () {}()``

``(function () {})()``

`!`airbnb JavaScript指南上标记的函数调用有一个好处

``````!function abc(){}();
!function bca(){}();``````

``````!function abc(){}();
(function bca(){})();``````

``````abcval = !function abc(){return true;}() // abcval equals false
bcaval = +function bca(){return true;}() // bcaval equals 1
zyxval = -function zyx(){return true;}() // zyxval equals -1
xyzval = ~function xyz(){return true;}() // your guess?``````

``````!function abc(/*no returns*/) {}()
+function bca() {/*no returns*/}()``````

``````!function abc(/*no returns*/) {}()
(function bca() {/*no returns*/})()``````

``````!function abc(/*no returns*/) {}()
^function bca() {/*no returns*/}()``````

``````^function abc(/*no returns*/) {}()
!function bca() {/*no returns*/}()``````

``````!false      // true
!true       // false
!isValid()  // is not valid``````

``````!!1    // true
!!0    // false``````

``var myVar = !function(){ return false; }();  // myVar contains true``

``function () { return false; }();  // syntax error``

``function (){}``

``(function (){}())``

``!function (){}()``

``````!function bool() { return false; }() // true
!function bool() { return true; }() // false``````

`!`在上面的示例中将省略SyntaxError

``function bool() { return true; }() // SyntaxError``

``(function bool() { return true; })() // true``

``````// I'm going to leave the closing () in all examples as invoking the function with just ! and () takes away from what's happening.

(function(){ return false; }());
=> false

!(function(){ return false; }());
=> true

!!(function(){ return false; }());
=> false

!!!(function(){ return false; }());
=> true``````

``````+(function(){ return false; }());
=> 0

-(function(){ return false; }());
=> -0

~(function(){ return false; }());
=> -1``````

``````+!(function(){ return false; }());
=> 1

-!(function(){ return false; }());
=> -1

!+(function(){ return false; }());
=> true

!-(function(){ return false; }());
=> true

~!(function(){ return false; }());
=> -2

~!!(function(){ return false; }());
=> -1

+~(function(){ return false; }());
+> -1``````

``(function( args ) {})()``

``!function ( args ) {}();``

`!` 将否定（相反）结果的期望值，即如果您有

``````var boy = true;
undefined
boy
true
!boy
false``````

``````function () {}();
SyntaxError: function statement requires a name
!function () {}();
true``````