javascript !javascript中的前一个函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5422585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:09:10  来源:igfitidea点击:

! preceding function in javascript?

javascript

提问by rg88

Possible Duplicate:
What does the exclamation mark do before the function?

可能的重复:
感叹号在函数之前有什么作用?

I saw a function formatted like this today for the first time:

今天第一次看到这样格式化的函数:

!function(){}();

What is the preceding exclamation mark for? I assume it functions the same as:

前面的感叹号是什么意思?我假设它的功能与:

(function(){})();

But... what's going on here?

但是……这是怎么回事?

回答by Mike Lewis

The preceding !takes the un-parseable statement, and allows it to to be parsed by the JS engine, which in turn returns true.

前面!的语句采用 un-parseable 语句,并允许它被 JS 引擎解析,然后返回 true。

function(){}();
SyntaxError: Unexpected token (

!function(){}();
>>true

回答by ThiefMaster

It simply makes the JavaScript parser parse it as an expression, which is necessary to execute it.

它只是让 JavaScript 解析器将其解析为一个表达式,这是执行它所必需的。

回答by Ming-Tang

I've tried it, it returned true. The function returns undefined, and !undefinedis true.

我试过了,它返回true。函数返回undefined,并且!undefined为真。

!function(){}();
^          ^ ^
C          A  B
  • A. function(){}is an empty anonymous function
  • B. ()executes the function (A), returning undefined
  • C. !negates undefined, which becomes true
  • A.function(){}是一个空的匿名函数
  • B.()执行函数(A),返回undefined
  • C.!否定undefined, 变成true

I think they used that trick for a code golf or an obfuscated code. It is a bad practice to practially use that

我认为他们将这个技巧用于代码高尔夫或混淆代码。实际使用它是一种不好的做法

Try javascript:alert(!function(){}())in your browser address bar

javascript:alert(!function(){}())在浏览器地址栏中尝试