包含内部和外部括号的闭包之间的差异 [英] Difference between closures with parentheses inside vs outside

查看:110
本文介绍了包含内部和外部括号的闭包之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释这些闭包之间的区别吗?有区别吗?我以前没有看到第二个例子(括号里面)。

Can someone explain what the difference is between these closures? Is there a difference? I haven't previously seen the second example (parentheses inside).

(function(a, b) {
    //...
})(x, y);

// Parentheses inside
(function(a, b) {
    //...
}(x, y));

这里,这些闭包之间有区别吗?

And here, is there a difference between these closures? Is there a scenario where there would be a difference?

FOO.Bar = (function() {
    //...
})();

FOO.Bar = (function() {
    //...
}());


推荐答案

否。在这两种情况下,它们是完全相同的。

No. In both cases they are exactly the same.

当你在括号中包装函数时会发生什么情况是从函数声明到函数表达式,可以立即调用。

What happens when you wrap your function in parentheses is that is goes from a function declaration to a function expression, which can be invoked immediately.

无论是在括号内还是后面都调用它。

Whether you invoke it within the parentheses or after does not matter. The "convension" has happened and you can thus invoke it.

实际上你可以这样做

FOO.Bar = function () {
    return 123;
}();

上面已经是一个函数表达式,因为你为一个属性赋值一个匿名函数 Bar FOO 上。

The above is already a function expression since you are assigning an anonymous function to a property Bar on FOO.

这篇关于包含内部和外部括号的闭包之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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