两种立即调用匿名函数的方法(function(d){}());和(function(x){})(); [英] Two ways of immediate call to anonymous function (function(d){ }() ); and (function(x){ } )();

查看:95
本文介绍了两种立即调用匿名函数的方法(function(d){}());和(function(x){})();的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

是“(function(){})()”和“(function(){}())”功能相同的JavaScript?

我有这些特殊字符的问题,我无法'找到一个好的答案。 (有没有人知道如何使用它们进行搜索?)

My question having these special characters, I couldn't find a good answer. (Does anyone know how to search with them?)

我已经看到两种模式可以立即调用匿名函数 http://jsfiddle.net/ukqS8/1/

I've seen two patterns to immediately calling anonymous functions http://jsfiddle.net/ukqS8/1/

(function(d) {
    document.write(d*2);
})(3);

(function(x) {
    document.write(x*2);
}(3));

不同之处在于放置(3):在右括号内部或外部。

The difference being where (3) is placed: inside or outside the closing parenthesis.

我在第二个案例中找到了一个很好的解释:

I found a good explanation for the second case here:

javascript function vs.(function(){...}());

我理解为 function(x){...} 创建一个函数对象,(3)成为它的参数,而enclosing()告诉解释器里面的内容是什么声明。

which I understood as function(x) {...} creates a function object, (3) becomes its argument, and the enclosing () tells the interpreter that what's inside is a statement.

在第一种情况下,它似乎使(函数(d){...})一个声明,不知何故也是一个函数,然后将(3)应用于这个语句/函数。

In the first case, it appears to make (function(d) {...}) a statement that somehow is also a function, and then apply (3) to this statement/function.

因此,它们似乎都以相同的方式执行。这里真的有区别吗?范围(我怀疑)?是否更优先选择?

So, they both appear to execute the same way. Is there really a difference here? Scope (I doubt it)? Is either option preferable?

推荐答案

您的理解不正确。

这些都是函数表达式;括号的位置在这里没有区别。

Those are both function expressions; the placement of the parentheses makes no difference here.

然而,可以有微妙的差异

这篇关于两种立即调用匿名函数的方法(function(d){}());和(function(x){})();的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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