javascript function vs.(function(){...}()); [英] javascript function vs. ( function() { ... } ());
本文介绍了javascript function vs.(function(){...}());的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我经常看到以下表达式:
I have often see expressions such as:
(function () {
var x = 1;
...
}());
我该如何解读?从语法上讲,这就是一个匿名的函数定义。
How do I interpret it? syntactically, this alone is a anonymous function definition.
function() {
...
}
之后的()是什么?为什么把它放在封闭的()?
what the () after that? and why put it in the enclosing ()?
谢谢
推荐答案
完全相同,只是在转换为函数表达式后立即调用它。
Exactly the same, except that it is being invoked immediately after being converted into a function expression.
// v-----first set of parentheses makes the function an expression
(function () {
var x = 1;
...
}());
// ^-----this set is used to invoke the function
相同好像你做了:
var myfunc = function () {
var x = 1;
...
};
myfunc();
或(类似)此:
var returnValue = function () {
var x = 1;
...
}();
摆脱名称,移动括号,你可以看到它们没有那么不同。
Get rid of the names, move the parentheses around, and you can see they're not that different.
这篇关于javascript function vs.(function(){...}());的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文