Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

javascript - 功能之前,感叹号有什么作用?(What does the exclamation mark do before the function?)

!function () {}();
  ask by Sebastian Otto translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

(不是特别有用。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...