JavaScript syntax 101. Here is a function declaration :
(JavaScript语法101。这是一个函数声明 :)
function foo() {}
Note that there's no semicolon: this is just a function declaration .
(请注意,这里没有分号:这只是一个函数声明 。)
You would need an invocation, foo()
, to actually run the function. (您需要一个调用foo()
才能实际运行该函数。)
Now, when we add the seemingly innocuous exclamation mark: !function foo() {}
it turns it into an expression .
(现在,当我们添加看似无害的感叹号: !function foo() {}
,它将变成一个表达式 。)
It is now a function expression . (现在它是一个函数表达式 。)
The !
(!
)
alone doesn't invoke the function, of course, but we can now put ()
at the end: !function foo() {}()
which has higher precedence than !
(当然,仅单独调用不会调用该函数,但是我们现在可以将()
放在最后: !function foo() {}()
优先级高于!
)
and instantly calls the function. (并立即调用该函数。)
So what the author is doing is saving a byte per function expression;
(因此,作者正在做的就是为每个函数表达式保存一个字节。)
a more readable way of writing it would be this: (更具可读性的书写方式是:)
(function(){})();
Lastly, !
(最后, !
)
makes the expression return true. (使表达式返回true。)
This is because by default all IIFE return undefined
, which leaves us with !undefined
which is true
. (这是因为默认情况下,所有IIFE返回的都是undefined
,这给我们留下!undefined
,它为true
。)
Not particularly useful. (不是特别有用。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…