Why use NOT operator on anonymous function call? (a la Knockout 2.1.0) [duplicate]

送分小仙女□ 提交于 2019-11-28 08:08:28

This is a concise way to form an immediately executed function expression.

Traditionally, people have used these two forms

(function(){ }()); // Recommended by Crockford
(function(){ })(); // What most people use

If you try to just use

function(){ }(); // Syntax error

it will be a syntax error, because it is interpreted as a function declaration rather than an expression. This is why you would need to wrap the function in parentheses.

But if you put a unary operator before the function declaration, you don't have to add a cosing parentheses, and it chops off one character of the code, which is a (very) tiny performance benefit. There are several unary operators that can be used for this same purpose

!function(){ }();
~function(){ }(); 
-function(){ }(); 
+function(){ }(); 

Because if you don't do something then it looks like a syntax error:

function(factory) { ... }(factoryDefinition);

Try it.

It's necessary to get the parser to a point where it expects an expression, so that the function keyword is recognized in that context. Otherwise, when the parser sees function as the first token in a statement, it expects a simple function declaration, and that can't be followed by a parenthesized argument list.

There are various alternatives, around each of which cluster various opinions.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!