! preceding function in javascript?
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?
The preceding !
takes the un-parseable statement, and allows it to to be parsed by the JS engine, which in turn returns true.
function(){}();
SyntaxError: Unexpected token (
!function(){}();
>>true
它只是使JavaScript解析器将其解析为一个表达式,这对执行它是必需的。
I've tried it, it returned true. The function returns undefined
, and !undefined
is true.
!function(){}();
^ ^ ^
C A B
function(){}
is an empty anonymous function ()
executes the function (A), returning undefined
!
negates undefined
, which becomes 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
上一篇: jQuery多个事件触发相同的功能
下一篇: ! 前面的函数在javascript中?