该功能之前感叹号做了什么? [英] What does the exclamation mark do before the function?

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

问题描述

 !function(){}(); 


解决方案

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

  function foo(){} 

请注意,没有分号:这只是声明的一个函数。你需要一个调用, foo(),才能真正运行这个函数。现在,当我们添加看起来无害的感叹号:!function foo(){} 它将它变成表达式。它现在是一个函数表达式



单独的不会调用函数,当然,但我们现在可以在最后加上()>:!function foo(){}()优先级高于并立即调用该函数。



因此,作者正在做的是保存字节每个函数表达式;一个更可读的写作方式是:

 (function(){})(); 

最后,使表达式返回true 。这是因为默认情况下所有的IIFE都会返回 undefined ,这给我们留下了!undefined ,它是。不是特别有用。


!function () {}();

解决方案

JavaScript syntax 101. Here is a function declaration:

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.

Now, when we add the seemingly innocuous exclamation mark: !function foo() {} it turns it into an expression. 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 ! 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. This is because by default all IIFE return undefined, which leaves us with !undefined which is true. Not particularly useful.

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

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