函数前的感叹号有什么作用? [英] What does the exclamation mark do before the function?

查看:39
本文介绍了函数前的感叹号有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

!function () {}();

推荐答案

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

JavaScript syntax 101. Here is a function declaration:

function foo() {}

注意没有分号:这只是一个函数声明.您需要调用 foo() 才能实际运行该函数.

Note that there's no semicolon: this is just a function declaration. You would need an invocation, foo(), to actually run the function.

现在,当我们添加看似无害的感叹号时:!function foo() {} 它将它变成了一个表达式.它现在是一个函数表达式.

Now, when we add the seemingly innocuous exclamation mark: !function foo() {} it turns it into an expression. It is now a function expression.

! 本身当然不会调用函数,但我们现在可以将 () 放在最后: !function foo() {}()! 具有更高的优先级并立即调用该函数.

The ! alone doesn't invoke the function, of course, but we can now put () at the end: !function foo() {}() which has higher precedence than ! 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(){})();

最后,! 使表达式返回真.这是因为默认情况下,所有立即调用的函数表达式 (IIFE) 都返回 undefined,这给我们留下了 !undefined,它是 true.不是特别有用.

Lastly, ! makes the expression return true. This is because by default all immediately invoked function expressions (IIFE) return undefined, which leaves us with !undefined which is true. Not particularly useful.

这篇关于函数前的感叹号有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆