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

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

问题描述

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

  //创建一个新的匿名函数,用作包装器
(function(){
//通常为全局的变量
var msg =感谢您访问!;

//将新函数绑定到全局对象
window.onunload = function(){
//其中使用'hidden'变量
alert(msg);
};
//关闭匿名函数并执行它
})();

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

 (function(msg){alert(msg)}) ('所以'); 

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

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

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



但是为什么这不起作用?

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

为什么需要在同一行?



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

解决方案

在函数定义后删除分号。

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

以上应该有效。



DEMO Page : https://jsfiddle.net/e7ooeq6m/



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



jQuery和$ question



编辑:



如果你看一下 ECMA脚本规范,有3种方法可以定义一个函数。 (第98页,第13节功能定义)



1。使用函数构造函数



  var sum = new函数('a','b','return a + b;'); 
alert(sum(10,20)); //提醒30



2。使用函数声明。



 函数sum(a,b)
{
返回a + b;
}

alert(sum(10,10)); //警报20;



3。函数表达式



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

alert(sum(5,5)); //提醒10

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



来自ECMA脚本规范:


FunctionDeclaration:
function Identifier (FormalParameterListopt){FunctionBody
}



FunctionExpression:
function Identifieropt(FormalParameterListopt){FunctionBody
}


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



这意味着以下内容有效。

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

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

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

alert(typeof(test2)); //提醒'undefined',惊喜!

test1(); //提醒'功能',因为test2是一个功能。

现场演示



将此与

进行比较

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

alert(typeof test1); //提醒'功能'

test1(); //提醒'功能'






拥有这方面的知识,让我们尝试分析你的代码。



当你有代码时,

  function(msg){alert(msg); } 

您创建了一个函数表达式。你可以通过将它包装在括号内来执行这个函数表达式。

 (function(msg){alert(msg);}) ('所以'); //提醒SO。 


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)})

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

but then why doesn't this work?

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

Why does it need to be in the same line?

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

解决方案

Drop the semicolon after the function definition.

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

Above should work.

DEMO Page: https://jsfiddle.net/e7ooeq6m/

I have discussed this kind of pattern in this post:

jQuery and $ questions

EDIT:

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

1. Using Function constructor

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

2. Using Function declaration.

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

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

3. Function Expression

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?

From ECMA Script specification:

FunctionDeclaration : function Identifier ( FormalParameterListopt ){ FunctionBody }

FunctionExpression : function Identifieropt ( FormalParameterListopt ){ FunctionBody }

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; }

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.

Live Demo

Compare this to

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

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

 test1(); //alerts 'function'


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

When you have code like,

    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天全站免登陆