否自调用功能? !function($){...}(window.jQuery); [英] negating self invoking function? !function ($) { ... }(window.jQuery);
问题描述
可能重复:
在功能之前,感叹号有什么作用?
Possible Duplicate:
What does the exclamation mark do before the function?
我在浏览Twitter Bootstrap JavaScript代码时,发现它们的所有插件都包装在否定自调用功能中.
I was looking through the Twitter Bootstrap JavaScript code and I noticed all their plugins are wrapped in negating self invoking functions.
我知道function ($) { ... }(window.jQuery);
立即调用该函数.
I am aware that function ($) { ... }(window.jQuery);
invokes the function immediately.
但是!
的作用是什么?
推荐答案
1),只要您这样做:
1) if you just do:
function () { /* ... */ }();
您将得到一个错误.
JS不允许您触发函数声明(由于可变提升"的概念,从技术上讲这不是正确的,但对于许多人来说更容易思考).
如果您使用声明性功能:
You will get an error.
JS will not allow you to fire off a function declaration (because of a concept of "variable hoisting", which isn't technically correct, but is much easier for a lot of people to think about).
If you use declarative functions:
function myFunc () { /* ... */ }
在创建范围变量之前,JS引擎将在您所在的范围内创建它们-即使var都在顶部,而函数都在底部.
The JS engine will create them in the scope you're in, before creating the variables of the scope -- even if the vars are all on the top and the functions are all on the bottom.
所以当你写的时候:
function myFunc () { /* ... */ }();
那里有一个错误,因为在当前作用域中甚至还不存在的var可能会在内部调用,这肯定会导致崩溃.
There's an error there, because the vars which don't even exist yet, in the current scope might be called inside, which is a guaranteed crash.
为进一步说明这一点,如果您不给函数声明起一个名字:
To further that, if you don't give your function-declaration a name:
function () { /* ... */ }
...然后那里有一个错误,无论如何,因为您还不能调用该函数,但是您无法获取它,因为它没有名称,也没有分配它到变量.
...then there's an error there, regardless, because you can't call the function yet, but you have no way of getting at it, because it doesn't have a name, and you didn't assign it to a variable.
()
或+
或!
之类的运算符-会迫使引擎评估接下来发生的事情的任何事物,都将允许您触发以下函数:
Operators like ()
or +
or !
-- anything which will force the engine to evaluate whatever comes next, will allow you to fire the function like:
+function () { /* ... */ }();
只要没有变量在监听return语句,就可以了.
As long as there is no variable listening for a return statement, you're fine.
2)另外,对于!function () { /*...*/ }();
,如果该函数没有自然的return语句,则它将返回undefined
.
以这种方式强制时,undefined
的反面是true
...
2) Additionally, in the case of !function () { /*...*/ }();
, if that function doesn't have a return statement naturally, then it will return undefined
.
The opposite of undefined
is true
when coerced in that way...
...因此,如果您真的想要,您可以执行以下操作:
...so if you really, REALLY wanted, you could do something like:
var success = !function () { /* ... */ }();
if (success) { doStuff(); }
这篇关于否自调用功能? !function($){...}(window.jQuery);的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!