为什么需要在同一行调用匿名函数? [英] Why do you need to invoke an anonymous function on the same line?

查看:27
本文介绍了为什么需要在同一行调用匿名函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读一些关于闭包的帖子,到处都看到了这个,但没有明确的解释它是如何工作的 - 每次我都被告知要使用它......:

I was reading some posts about closures and saw this everywhere, but there is no clear explanation how it works - everytime I was just told to use it...:

// Create a new anonymous function, to use as a wrapper
(function(){
    // The variable that would, normally, be global
    var msg = "Thanks for visiting!";

    // Binding a new function to a global object
    window.onunload = function(){
        // Which uses the 'hidden' variable
        alert( msg );
    };
// Close off the anonymous function and execute it
})();

好的,我知道我们将创建新的匿名函数然后执行它.所以在那之后这个简单的代码应该可以工作(并且确实如此):

Ok I see that we will create new anonymous function and then execute it. So after that this simple code should work (and it does):

(function (msg){alert(msg)})('SO');

我的问题是这里发生了什么样的魔法?当我写道:

My question is what kind of magic happens here? I thought that when I wrote:

(function (msg){alert(msg)})

然后将创建一个新的未命名函数,如函数 ""(msg) ...

then a new unnamed function would be created like function ""(msg) ...

但是为什么这不起作用?

but then why doesn't this work?

(function (msg){alert(msg)});
('SO');

为什么需要在同一行?

你能给我指点一些帖子或者给我一个解释吗?

Could you please point me some posts or give me an explanation?

推荐答案

去掉函数定义后的分号.

Drop the semicolon after the function definition.

(function (msg){alert(msg)})
('SO');

以上应该有效.

演示页面:https://jsfiddle.net/e7ooeq6m/

我在这篇文章中讨论了这种模式:

I have discussed this kind of pattern in this post:

jQuery 和 $ 问题

如果您查看 ECMA 脚本规范,有 3 种方法可以定义函数.(第 98 页,第 13 节函数定义)

If you look at ECMA script specification, there are 3 ways you can define a function. (Page 98, Section 13 Function Definition)

var sum = new Function('a','b', 'return a + b;');
alert(sum(10, 20)); //alerts 30

2.使用函数声明.

function sum(a, b)
{
    return a + b;
}

alert(sum(10, 10)); //Alerts 20;

3.函数表达式

var sum = function(a, b) { return a + b; }

alert(sum(5, 5)); // alerts 10

那么你可能会问,声明和表达式有什么区别?

So you may ask, what's the difference between declaration and expression?

来自 ECMA 脚本规范:

From ECMA Script specification:

函数声明:函数标识符( FormalParameterListopt ){ FunctionBody}

FunctionDeclaration : function Identifier ( FormalParameterListopt ){ FunctionBody }

函数表达式:function Identifieropt ( FormalParameterListopt ){ FunctionBody}

FunctionExpression : function Identifieropt ( FormalParameterListopt ){ FunctionBody }

如果您注意到,'identifier' 是函数表达式的可选.当您不提供标识符时,您就创建了一个匿名函数.这并不意味着您不能指定标识符.

If you notice, 'identifier' is optional for function expression. And when you don't give an identifier, you create an anonymous function. It doesn't mean that you can't specify an identifier.

这意味着以下内容有效.

This means following is valid.

var sum = function mySum(a, b) { return a + b; }

需要注意的重要一点是,您只能在 mySum 函数体内使用 'mySum',而不能在外部使用.请参阅以下示例:

Important point to note is that you can use 'mySum' only inside the mySum function body, not outside. See following example:

var test1 = function test2() { alert(typeof test2); }

alert(typeof(test2)); //alerts 'undefined', surprise! 

test1(); //alerts 'function' because test2 is a function.

现场演示

对比一下

 function test1() { alert(typeof test1) };

 alert(typeof test1); //alerts 'function'

 test1(); //alerts 'function'

<小时>

有了这些知识,让我们尝试分析您的代码.


Armed with this knowledge, let's try to analyze your code.

当你有这样的代码时,

    function(msg) { alert(msg); }

您创建了一个函数表达式.您可以通过将其包裹在括号内来执行此函数表达式.

You created a function expression. And you can execute this function expression by wrapping it inside parenthesis.

    (function(msg) { alert(msg); })('SO'); //alerts SO.

这篇关于为什么需要在同一行调用匿名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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