自我执行功能不起作用? [英] Self Executing function doesnt work?

查看:91
本文介绍了自我执行功能不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有代码:

function (i)
{
    alert(i);
}(3);

我不明白为什么我看不到警报。

I don't understand why I don't see the alert.

这种语法是什么意思?

What does this syntax mean?

为什么这段代码:

( function (i)
{
    alert(i);
}(3))();         

有效吗?

有什么区别?

我缺少什么?

推荐答案

第一个片段将被解释为函数声明,它需要一个名称,而您的函数没有名称。所以这会导致错误。

The first snippet will be interpreted as function declaration, which needs a name and your function does not have one. So this will result in an error.

用括号括起函数定义会使函数被解释为函数表达式,这不需要一个名字,所以它是有效的JavaScript。

Surrounding the function definition with parenthesis makes the function to be interpreted as function expression which doesn't need a name, so it is valid JavaScript.

虽然看起来你正在那里进行两次调用。它应该是

Though it seems you are making two invocations there. It should either be

(function(i){ alert(i); }(3));

(function(i){ alert(i); })(3); 

通常你可以在括号中使用函数表达式(一切都在那里被评估为表达式)或在右边赋值表达式的一面( var a = function ... )。

Typically you can have function expression either in parenthesis (everything is evaluated as expression there) or at the right side of an assignment expression (var a = function...).

请参阅 ECMAScript 5规范的第13部分


FunctionDeclaration

功能 标识符 FormalParameterList opt ){ FunctionBody }

FunctionExpression

功能 标识符 opt FormalParameterList opt ){ FunctionBody }

这篇关于自我执行功能不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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