为什么需要在同一行调用匿名函数?

发布于 2024-07-28 22:25:26 字数 856 浏览 4 评论 0原文

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

// 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
})();

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

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

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

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

然后将创建一个新的未命名函数,如函数“”(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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

与风相奔跑 2024-08-04 22:25:26

删除函数定义后面的分号。

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

以上应该有效。

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

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

jQuery 和 $ 问题

编辑:

如果您查看 < a href="http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf" rel="noreferrer">ECMA 脚本规范,有 3 种方法可以定义一个函数。 (第 98 页,第 13 节函数定义)

1. 使用函数构造函数

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

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

来自 ECMA 脚本规范:

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

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

您注意到,“标识符”对于函数表达式来说是可选。 当您不提供标识符时,您将创建一个匿名函数。 这并不意味着您不能指定标识符。

这意味着以下内容是有效的。

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

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

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'

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

当您有类似的代码时,

    function(msg) { alert(msg); }

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

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

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.
终弃我 2024-08-04 22:25:26

这称为自调用函数。

当您调用 (function(){}) 时,您所做的就是返回一个函数对象。 当您将 () 附加到它时,它就会被调用并执行主体中的任何内容。 ; 表示语句结束,这就是第二次调用失败的原因。

It's called a self-invoked function.

What you are doing when you call (function(){}) is returning a function object. When you append () to it, it is invoked and anything in the body is executed. The ; denotes the end of the statement, that's why the 2nd invocation fails.

不一样的天空 2024-08-04 22:25:26

我发现令人困惑的一件事是“()”是分组运算符。

这是您的基本声明函数。

前任。 1:

var message = 'SO';

function foo(msg) {
    alert(msg);
}

foo(message);

函数是对象,可以分组。 因此,让我们在函数周围加上括号。

前任。 2:

var message = 'SO';

function foo(msg) {  //declares foo
    alert(msg);
}

(foo)(message);     // calls foo

现在我们可以使用基本替换来声明我们调用的函数,而不是声明并立即调用同一个函数。

前任。 3.

var message = 'SO';

(function foo(msg) {
    alert(msg);
})(message);          // declares & calls foo

最后,我们不需要额外的 foo,因为我们不使用名称来调用它! 函数可以是匿名的。

前任。 4.

var message = 'SO';

(function (msg) {   // remove unnecessary reference to foo
    alert(msg);
})(message);

要回答您的问题,请参阅示例 2。您的第一行声明了一些无名函数并将其分组,但不调用它。 第二行对一个字符串进行分组。 两者什么都不做。 (文森特的第一个例子。)

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

(foo); 
(msg); //Still nothing.

但是

(foo)
(msg); //works

One thing I found confusing is that the "()" are grouping operators.

Here is your basic declared function.

Ex. 1:

var message = 'SO';

function foo(msg) {
    alert(msg);
}

foo(message);

Functions are objects, and can be grouped. So let's throw parens around the function.

Ex. 2:

var message = 'SO';

function foo(msg) {  //declares foo
    alert(msg);
}

(foo)(message);     // calls foo

Now instead of declaring and right-away calling the same function, we can use basic substitution to declare it as we call it.

Ex. 3.

var message = 'SO';

(function foo(msg) {
    alert(msg);
})(message);          // declares & calls foo

Finally, we don't have a need for that extra foo because we're not using the name to call it! Functions can be anonymous.

Ex. 4.

var message = 'SO';

(function (msg) {   // remove unnecessary reference to foo
    alert(msg);
})(message);

To answer your question, refer back to Example 2. Your first line declares some nameless function and groups it, but does not call it. The second line groups a string. Both do nothing. (Vincent's first example.)

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

(foo); 
(msg); //Still nothing.

But

(foo)
(msg); //works
心的位置 2024-08-04 22:25:26

匿名函数不是名称为“”的函数。 它只是一个没有名称的函数。

与 JavaScript 中的任何其他值一样,函数不需要创建名称。 尽管将其实际绑定到名称(就像任何其他值一样)要有用得多。

但与任何其他值一样,有时您希望使用它而不将其绑定到名称。 这就是自调用模式。

这是一个函数和一个数字,未绑定,它们不执行任何操作并且永远无法使用:

function(){ alert("plop"); }
2;

因此我们必须将它们存储在变量中才能使用它们,就像任何其他值一样:

var f = function(){ alert("plop"); }
var n = 2;

您还可以使用语法糖来绑定函数到变量:

function f(){ alert("plop"); }
var n = 2;

但是,如果不需要命名它们,并且会导致更多混乱和可读性降低,那么您可以立即使用它们。

(function(){ alert("plop"); })(); // will display "plop"
alert(2 + 3); // will display 5

在这里,我的函数和数字没有绑定到变量,但它们仍然可以使用。

这样看来,自调用函数并没有什么实际价值。 但您必须记住,JavaScript 作用域分隔符是函数而不是块 ({})。

因此,自调用函数实际上与 C++、C# 或 Java 块具有相同的含义。 这意味着内部创建的变量不会“泄漏”到作用域之外。 这在 JavaScript 中非常有用,可以避免污染全局范围。

An anonymous function is not a function with the name "". It is simply a function without a name.

Like any other value in JavaScript, a function does not need a name to be created. Though it is far more useful to actually bind it to a name just like any other value.

But like any other value, you sometimes want to use it without binding it to a name. That's the self-invoking pattern.

Here is a function and a number, not bound, they do nothing and can never be used:

function(){ alert("plop"); }
2;

So we have to store them in a variable to be able to use them, just like any other value:

var f = function(){ alert("plop"); }
var n = 2;

You can also use syntatic sugar to bind the function to a variable:

function f(){ alert("plop"); }
var n = 2;

But if naming them is not required and would lead to more confusion and less readability, you could just use them right away.

(function(){ alert("plop"); })(); // will display "plop"
alert(2 + 3); // will display 5

Here, my function and my numbers are not bound to a variable, but they can still be used.

Said like this, it looks like self-invoking function have no real value. But you have to keep in mind that JavaScript scope delimiter is the function and not the block ({}).

So a self-invoking function actually has the same meaning as a C++, C# or Java block. Which means that variable created inside will not "leak" outside the scope. This is very useful in JavaScript in order not to pollute the global scope.

追我者格杀勿论 2024-08-04 22:25:26

这就是 JavaScript 的工作原理。 您可以声明一个命名函数:

function foo(msg){
   alert(msg);
}

并调用它:

foo("Hi!");

或者,您可以声明一个匿名函数:

var foo = function (msg) {
    alert(msg);
}

并调用它:

foo("Hi!");

或者,您永远不能将函数绑定到名称:

(function(msg){
   alert(msg);
 })("Hi!");

函数也可以返回函数:

function make_foo() {
    return function(msg){ alert(msg) };
}

(make_foo())("Hi!");

定义的任何变量都毫无价值make_foo 主体中的“var”将被 make_foo 返回的每个函数封闭。 这是一个闭包,这意味着一个函数对值所做的任何更改都将被另一个函数看到。

如果您愿意,这可以让您封装信息:

function make_greeter(msg){
    return function() { alert(msg) };
}

var hello = make_greeter("Hello!");

hello();

这就是除 Java 之外的几乎所有编程语言的工作方式。

It's just how JavaScript works. You can declare a named function:

function foo(msg){
   alert(msg);
}

And call it:

foo("Hi!");

Or, you can declare an anonymous function:

var foo = function (msg) {
    alert(msg);
}

And call that:

foo("Hi!");

Or, you can just never bind the function to a name:

(function(msg){
   alert(msg);
 })("Hi!");

Functions can also return functions:

function make_foo() {
    return function(msg){ alert(msg) };
}

(make_foo())("Hi!");

It's worth nothing that any variables defined with "var" in the body of make_foo will be closed over by each function returned by make_foo. This is a closure, and it means that the any change made to the value by one function will be visible by another.

This lets you encapsulate information, if you desire:

function make_greeter(msg){
    return function() { alert(msg) };
}

var hello = make_greeter("Hello!");

hello();

It's just how nearly every programming language but Java works.

不及他 2024-08-04 22:25:26

您显示的代码

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

两个语句组成。 第一个是一个产生函数对象的表达式(该对象随后将被垃圾收集,因为它没有被保存)。 第二个是产生字符串的表达式。 要将函数应用于字符串,您需要在创建函数时将字符串作为参数传递给函数(上面也显示了这一点),或者您需要将函数实际存储在变量中,以便您可以稍后在您闲暇时使用它。 像这样:

var f = (function (msg){alert(msg)});
f('SO');

请注意,通过将匿名函数(lambda 函数)存储在变量中,您实际上是在给它命名。 因此,您也可以定义一个常规函数:

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

The code you show,

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

consist of two statements. The first is an expression which yields a function object (which will then be garbage collected because it is not saved). The second is an expression which yields a string. To apply the function to the string, you either need to pass the string as an argument to the function when it is created (which you also show above), or you will need to actually store the function in a variable, so that you can apply it at a later time, at your leisure. Like so:

var f = (function (msg){alert(msg)});
f('SO');

Note that by storing an anonymous function (a lambda function) in a variable, your are effectively giving it a name. Hence you may just as well define a regular function:

function f(msg) {alert(msg)};
f('SO');
对不⑦ 2024-08-04 22:25:26

总结之前的评论:

function() {
  alert("hello");
}();

当未分配给变量时,会产生语法错误。 代码被解析为函数语句(或定义),这导致右括号在语法上不正确。 在函数部分周围添加括号告诉解释器(和程序员)这是一个函数表达式(或调用),如

(function() {
  alert("hello");
})();

这是一个自调用函数,这意味着它是匿名创建的并立即运行,因为调用发生在同一行中声明的地方。 此自调用函数使用熟悉的语法来指示调用无参数函数,并在函数名称周围添加括号:(myFunction)();

一个很好的SO讨论JavaScript函数语法< /a>.

In summary of the previous comments:

function() {
  alert("hello");
}();

when not assigned to a variable, yields a syntax error. The code is parsed as a function statement (or definition), which renders the closing parentheses syntactically incorrect. Adding parentheses around the function portion tells the interpreter (and programmer) that this is a function expression (or invocation), as in

(function() {
  alert("hello");
})();

This is a self-invoking function, meaning it is created anonymously and runs immediately because the invocation happens in the same line where it is declared. This self-invoking function is indicated with the familiar syntax to call a no-argument function, plus added parentheses around the name of the function: (myFunction)();.

There is a good SO discussion JavaScript function syntax.

深海少女心 2024-08-04 22:25:26

我对提问者的问题的理解是:

这个魔法是如何发挥作用的:

(function(){}) ('input')   // Used in his example

我可能是错的。 然而,人们熟悉的通常做法是:

(function(){}('input') )

原因是 JavaScript 括号又名 () 不能包含语句,当解析器遇到 function 关键字时,它知道将其解析为函数表达式而不是函数声明。

来源:博客文章立即调用函数表达式 (IIFE)< /a>

My understanding of the asker's question is such that:

How does this magic work:

(function(){}) ('input')   // Used in his example

I may be wrong. However, the usual practice that people are familiar with is:

(function(){}('input') )

The reason is such that JavaScript parentheses AKA (), can't contain statements and when the parser encounters the function keyword, it knows to parse it as a function expression and not a function declaration.

Source: blog post Immediately-Invoked Function Expression (IIFE)

撩心不撩汉 2024-08-04 22:25:26

不带括号的示例:(

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

这是 void 的唯一真正用法,据我所知)

var a = function (msg) { alert(msg); }
('SO');

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

也可以。 void 导致表达式求值,以及赋值和爆炸。 最后一个适用于 ~+-deletetypeof、一些一元运算符(void 也是其中之一)。 由于需要变量,所以不工作当然是 ++--

换行符是不必要的。

examples without brackets:

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

(this is the only real use of void, afaik)

or

var a = function (msg) { alert(msg); }
('SO');

or

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

work as well. the void is causing the expression to evaluate, as well as the assignment and the bang. the last one works with ~, +, -, delete, typeof, some of the unary operators (void is one as well). not working are of couse ++, -- because of the requirement of a variable.

the line break is not necessary.

猫烠⑼条掵仅有一顆心 2024-08-04 22:25:26

这个答案与问题并不严格相关,但您可能有兴趣发现这种语法特征并不是函数所特有的。 例如,我们总是可以做这样的事情:

alert(
    {foo: "I am foo", bar: "I am bar"}.foo
); // alerts "I am foo"

与函数相关。 由于它们是继承自 Function.prototype 的对象,因此我们可以执行以下操作:

Function.prototype.foo = function () {
    return function () {
        alert("foo");
    };
};

var bar = (function () {}).foo();

bar(); // alerts foo

而且您知道,我们甚至不必用括号将函数括起来即可执行它们。 无论如何,只要我们尝试将结果赋值给一个变量即可。

var x = function () {} (); // this function is executed but does nothing

function () {} (); // syntax error

一旦声明函数,您可以对函数执行的另一件事是对它们调用 new 运算符并获取一个对象。 以下是等效的:

var obj = new function () {
    this.foo = "bar";
};

var obj = {
    foo : "bar"
};

This answer is not strictly related to the question, but you might be interested to find out that this kind of syntax feature is not particular to functions. For example, we can always do something like this:

alert(
    {foo: "I am foo", bar: "I am bar"}.foo
); // alerts "I am foo"

Related to functions. As they are objects, which inherit from Function.prototype, we can do things like:

Function.prototype.foo = function () {
    return function () {
        alert("foo");
    };
};

var bar = (function () {}).foo();

bar(); // alerts foo

And you know, we don't even have to surround functions with parenthesis in order to execute them. Anyway, as long as we try to assign the result to a variable.

var x = function () {} (); // this function is executed but does nothing

function () {} (); // syntax error

One other thing you may do with functions, as soon as you declare them, is to invoke the new operator over them and obtain an object. The following are equivalent:

var obj = new function () {
    this.foo = "bar";
};

var obj = {
    foo : "bar"
};
稚然 2024-08-04 22:25:26

JavaScript 函数还有一项属性。 如果你想递归调用相同的匿名函数。

(function forInternalOnly(){

  //you can use forInternalOnly to call this anonymous function
  /// forInternalOnly can be used inside function only, like
  var result = forInternalOnly();
})();

//this will not work
forInternalOnly();// no such a method exist

There is one more property JavaScript function has. If you want to call same anonymous function recursively.

(function forInternalOnly(){

  //you can use forInternalOnly to call this anonymous function
  /// forInternalOnly can be used inside function only, like
  var result = forInternalOnly();
})();

//this will not work
forInternalOnly();// no such a method exist
情未る 2024-08-04 22:25:26

它是一个自动执行的匿名函数。 第一组括号包含要执行的表达式,第二组括号执行这些表达式。

(function () {
    return ( 10 + 20 );
})();

Peter Michaux 在一对重要的括号中讨论了差异。

当尝试隐藏父命名空间中的变量时,这是一个有用的构造。 函数内的所有代码都包含在函数的私有范围内,这意味着它根本无法从函数外部访问,从而使其真正成为私有的。

请参阅:

  1. 闭包(计算机科学)
  2. JavaScript 命名空间
  3. 一对重要的 Javascript 括号

It is a self-executing anonymous function. The first set of brackets contain the expressions to be executed, and the second set of brackets executes those expressions.

(function () {
    return ( 10 + 20 );
})();

Peter Michaux discusses the difference in An Important Pair of Parentheses.

It is a useful construct when trying to hide variables from the parent namespace. All the code within the function is contained in the private scope of the function, meaning it can't be accessed at all from outside the function, making it truly private.

See:

  1. Closure (computer science)
  2. JavaScript Namespacing
  3. Important Pair of Javascript Parentheses
孤独患者 2024-08-04 22:25:26

另一种观点

首先,你可以声明一个匿名函数:

var foo = function(msg){
 alert(msg);
}

然后你调用它:

foo ('Few');

因为 foo = function(msg){alert(msg);} 所以你可以替换 foo > as:

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

但是你应该将整个匿名函数包裹在一对大括号内,以避免解析时声明函数的语法错误。 这样一来

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

,我就很容易理解了。

Another point of view

First, you can declare an anonymous function:

var foo = function(msg){
 alert(msg);
}

Then you call it:

foo ('Few');

Because foo = function(msg){alert(msg);} so you can replace foo as:

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

But you should wrap your entire anonymous function inside pair of braces to avoid syntax error of declaring function when parsing. Then we have,

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

By this way, It's easy understand for me.

梦言归人 2024-08-04 22:25:26

当您这样做时:

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

由于分号,您在 ('SO') 之前结束了该函数。 如果你只写:

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

它会起作用。

工作示例: http://jsfiddle.net/oliverni/dbVjg/

When you did:

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

You ended the function before ('SO') because of the semicolon. If you just write:

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

It will work.

Working example: http://jsfiddle.net/oliverni/dbVjg/

寂寞陪衬 2024-08-04 22:25:26

它不起作用的简单原因不是因为 ; 指示匿名函数的结束。 这是因为如果函数调用末尾没有(),那么它就不是函数调用。 也就是说,

function help() {return true;}

如果您调用 result = help(); 这是对函数的调用,并将返回 true。

如果您调用 result = help; 这不是一个调用。 在这种分配中,帮助被视为要分配给结果的数据。

您所做的是通过添加分号来声明/实例化一个匿名函数,

(function (msg) { /* Code here */ });

然后尝试仅使用括号在另一个语句中调用它...显然是因为该函数没有名称,但这不起作用:

('SO');

解释器看到括号在第二行作为新的指令/语句,因此它不起作用,即使您这样做:

(function (msg){/*code here*/});('SO');

它仍然不起作用,但是当您删除分号时它会起作用,因为解释器会忽略空格和回车符并且将完整的代码视为一条语句。

(function (msg){/*code here*/})        // This space is ignored by the interpreter
('SO');

结论:函数调用不是最后没有 () 的函数调用,除非在特定条件下,例如被另一个函数调用,即 onload='help' 甚至会执行帮助函数虽然括号不包括在内。 我相信 setTimeout 和 setInterval 也允许这种类型的函数调用,而且我也相信解释器无论如何都会在幕后添加括号,这让我们回到“函数调用不是没有括号的函数调用”。

The simple reason why it doesn't work is not because of the ; indicating the end of the anonymous function. It is because without the () on the end of a function call, it is not a function call. That is,

function help() {return true;}

If you call result = help(); this is a call to a function and will return true.

If you call result = help; this is not a call. It is an assignment where help is treated like data to be assigned to result.

What you did was declaring/instantiating an anonymous function by adding the semicolon,

(function (msg) { /* Code here */ });

and then tried to call it in another statement by using just parentheses... Obviously because the function has no name, but this will not work:

('SO');

The interpreter sees the parentheses on the second line as a new instruction/statement, and thus it does not work, even if you did it like this:

(function (msg){/*code here*/});('SO');

It still doesn't work, but it works when you remove the semicolon because the interpreter ignores white spaces and carriages and sees the complete code as one statement.

(function (msg){/*code here*/})        // This space is ignored by the interpreter
('SO');

Conclusion: a function call is not a function call without the () on the end unless under specific conditions such as being invoked by another function, that is, onload='help' would execute the help function even though the parentheses were not included. I believe setTimeout and setInterval also allow this type of function call too, and I also believe that the interpreter adds the parentheses behind the scenes anyhow which brings us back to "a function call is not a function call without the parentheses".

紫﹏色ふ单纯 2024-08-04 22:25:26
(function (msg){alert(msg)})
('SO');

这是许多 JavaScript 框架使用匿名函数作为闭包的常见方法。

编译代码时会自动调用此函数。

如果将 ; 放在第一行,编译器会将其视为两行不同的行。 所以你不能得到与上面相同的结果。

这也可以写成:

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

有关更多详细信息,请查看JavaScript/匿名函数

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

This is a common method of using an anonymous function as a closure which many JavaScript frameworks use.

This function called is automatically when the code is compiled.

If placing ; at the first line, the compiler treated it as two different lines. So you can't get the same results as above.

This can also be written as:

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

For more details, look into JavaScript/Anonymous Functions.

苍白女子 2024-08-04 22:25:26

IIFE 只是划分函数并隐藏 msg 变量,以免“污染”全局命名空间。 实际上,除非您正在构建价值十亿美元的网站,否则只需保持简单并按照下面的操作即可。

var msg = "later dude";
window.onunload = function(msg){
  alert( msg );
};

您可以使用揭示模块模式来命名您的 msg 属性,例如:

var myScript = (function() {
    var pub = {};
    //myscript.msg
    pub.msg = "later dude";
    window.onunload = function(msg) {
        alert(msg);
    };
    //API
    return pub;
}());

The IIFE simply compartmentalizes the function and hides the msg variable so as to not "pollute" the global namespace. In reality, just keep it simple and do like below unless you are building a billion dollar website.

var msg = "later dude";
window.onunload = function(msg){
  alert( msg );
};

You could namespace your msg property using a Revealing Module Pattern like:

var myScript = (function() {
    var pub = {};
    //myscript.msg
    pub.msg = "later dude";
    window.onunload = function(msg) {
        alert(msg);
    };
    //API
    return pub;
}());
挽袖吟 2024-08-04 22:25:26

匿名函数是动态声明的函数
运行。 它们被称为匿名函数,因为它们不是
以与普通函数相同的方式命名。

匿名函数是使用函数运算符来声明的
函数声明的。 您可以使用函数运算符
在可以有效放置表达式的位置创建一个新函数。 为了
例如,您可以声明一个新函数作为参数
函数调用或分配另一个对象的属性。

这是命名函数的典型示例:

function flyToTheMoon() {
    alert("Zoom! Zoom! Zoom!"); 
}

flyToTheMoon(); 

这是创建为匿名函数的相同示例:

var flyToTheMoon = function() {
   alert("Zoom! Zoom! Zoom!"); 
}

flyToTheMoon();

有关详细信息,请阅读 http://helephant.com/2008/08/23/javascript-anonymous-functions/

Anonymous functions are functions that are dynamically declared at
runtime. They’re called anonymous functions because they aren’t
given a name in the same way as normal functions.

Anonymous functions are declared using the function operator instead
of the function declaration. You can use the function operator to
create a new function wherever it’s valid to put an expression. For
example, you could declare a new function as a parameter to a
function call or to assign a property of another object.

Here’s a typical example of a named function:

function flyToTheMoon() {
    alert("Zoom! Zoom! Zoom!"); 
}

flyToTheMoon(); 

Here’s the same example created as an anonymous function:

var flyToTheMoon = function() {
   alert("Zoom! Zoom! Zoom!"); 
}

flyToTheMoon();

For details please read http://helephant.com/2008/08/23/javascript-anonymous-functions/

东京女 2024-08-04 22:25:26

匿名函数意味着您可以动态定义一个函数,以便它根据您提供的输入生成输出。 除非您没有提供输入。 相反,你在第二行写了一些东西(“SO”); - 与功能无关的独立声明。 你期待什么? :)

Anonymous functions are meant to be one-shot deal where you define a function on the fly so that it generates an output from you from an input that you are providing. Except that you did not provide the input. Instead, you wrote something on the second line ('SO'); - an independent statement that has nothing to do with the function. What did you expect? :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文