立即调用的简单 JavaScript 函数不起作用...为什么?

发布于 2024-08-02 17:32:12 字数 270 浏览 6 评论 0原文

任何人都可以解释为什么这有效:

var sayHello = function (name) {
   alert("Hello there " + name + "!");
}("Mike");

虽然这不起作用:

function sayHello (name) {
   alert("Hello there " + name + "!");
}("Mike");

Mike Peat

Can anybody explain why this works:

var sayHello = function (name) {
   alert("Hello there " + name + "!");
}("Mike");

While this does not:

function sayHello (name) {
   alert("Hello there " + name + "!");
}("Mike");

Mike Peat

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

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

发布评论

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

评论(6

自找没趣 2024-08-09 17:32:12

这里您需要了解的是 Javascript 中的 FunctionExpression 和 FunctionDeclaration 之间的区别。

当您用括号 -

(function sayHello (name) {
   alert("Hello there " + name + "!");
})("Mike");

- 括住函数时,从技术上讲,您可以对其应用分组运算符。一旦应用,整体产生式就不再是一个FunctionDeclarataion,而是一个FunctionExpression。比较 -

function foo(){ } // FunctionDeclaration

(function foo(){ }); // FunctionExpresson
typeof function(){ }; // FunctionExpression
new function(){ }; // FunctionExpression

FunctionExpression(与FunctionDeclaration相反),就像任何其他MemberExpresson一样可以附加参数(“( " 和 ")") 并将导致函数调用。这正是在第一个示例中调用函数而不是在第二个示例中调用函数的原因。

请注意,FunctionExpression 允许具有可选的标识符(与 FunctionDeclaration 必须始终有一个相反),因此您可以轻松省略“ sayHello”并最终得到所谓的匿名函数表达式 -

(function(){
  alert('...');
});

您可以查看我关于命名函数表达式的文章,它更详细地探讨了函数表达式和函数声明之间差异的微妙细节。

All you have to understand here is the difference between FunctionExpressions and FunctionDeclarations in Javascript.

When you surround function with parenthesis -

(function sayHello (name) {
   alert("Hello there " + name + "!");
})("Mike");

- you, technically, apply a grouping operator to it. Once applied, overall production is no longer a FunctionDeclarataion, but a FunctionExpression. Compare -

function foo(){ } // FunctionDeclaration

(function foo(){ }); // FunctionExpresson
typeof function(){ }; // FunctionExpression
new function(){ }; // FunctionExpression

FunctionExpression (contrary to FunctionDeclaration), just like any other MemberExpresson can be appended with Arguments ("(" and ")") and will result in function invocation. This is exactly why function is being called in your first example and not in a second.

Note that FunctionExpressions are allowed to have optional Identifiers (contrary to FunctionDeclarations which must always have one), so you can easily omit "sayHello" and end up with so-called anonymous function expression -

(function(){
  alert('...');
});

You can check out my article on named function expressions, which delves into subtle details of difference between function expressions and function declarations in much more detail.

不知所踪 2024-08-09 17:32:12

你的第二个代码实际上是:

function sayHello (name) {
   alert("Hello there " + name + "!");
}

("Mike");

所以你首先声明函数“sayHello”,然后执行“语句”:

("Mike");

它什么也不做。

Your second code is actually:

function sayHello (name) {
   alert("Hello there " + name + "!");
}

("Mike");

So you are first declaring function "sayHello", and then you're executing the "statement":

("Mike");

which does nothing.

錯遇了你 2024-08-09 17:32:12

这将起作用:

    (function sayHello (name) {
        alert("Hello there " + name + "!");
     })("Mike");

注意包裹函数本身的括号。您还可以删除函数名称“sayHello”,它仍然可以工作。至于为什么?我不积极。也许通过将其分配给变量而不使用包装 (),您实际上将其分配给 sayHello,然后在 say hello 上执行,而不是在匿名函数上执行。

This will work:

    (function sayHello (name) {
        alert("Hello there " + name + "!");
     })("Mike");

Notice the parens wrapping the function itself. You can also remove the function name "sayHello" and it will still work. As far as why? I'm not positive. Maybe its that by assigning it to a variable and not using the wrapping ()'s, you are actually assigning it to sayHello and then executing on say hello, not the anonymous function.

盛夏已如深秋| 2024-08-09 17:32:12
var sayHello = function (name) {
   alert("Hello there " + name + "!");
}("Mike");

这将创建一个匿名函数并立即使用“Mike”参数调用它。
然后该函数调用的返回值被分配给变量sayHello。

function sayHello (name) {
   alert("Hello there " + name + "!");
}("Mike");

这只是定义了一个名为 sayHello 的普通函数,并且函数语句在结束 } 后结束。
然后是(“Mike”)语句,该语句有效,但不执行任何操作。

var sayHello = function (name) {
   alert("Hello there " + name + "!");
}("Mike");

This creates an anonymous function and calls it right away with the "Mike" parameter.
Then the return value of that function call is assigned to the variable sayHello.

function sayHello (name) {
   alert("Hello there " + name + "!");
}("Mike");

This just defines a normal function with the name sayHello and the function statement ends after the closing }.
Then follows the ("Mike") statement which is valid, but does nothing.

绝不放开 2024-08-09 17:32:12

在调用它之前将函数定义包围在 () 中:

(function sayHello(name) {
   alert("Hello there " + name + "!");
})("Mike");

// however -- 
alert(typeof sayHello);  // undefined

因此,如果您想做类似的事情 - 您不妨将其设为匿名函数:

(function(name) {
   alert("Hello there " + name + "!");
})("Mike");

而且我不确定它是必需的 - 但是为了安全 - 每当我使用这样的闭包时,我总是将其包装在 ()

Surrounding the function definition in () before calling it works:

(function sayHello(name) {
   alert("Hello there " + name + "!");
})("Mike");

// however -- 
alert(typeof sayHello);  // undefined

So if you want to do something like that - you might as well just make it an anonymous function:

(function(name) {
   alert("Hello there " + name + "!");
})("Mike");

And I'm not sure it's required - but for safety - anytime I'm using a closure like that I always wrap it in ()

北方的韩爷 2024-08-09 17:32:12

编辑是因为我的答案错误地阅读了原始帖子:

由于您的函数不再被分配为 lambda 函数到某个值,因此之后使用 (“Mike”) 调用该函数将不起作用,因为没有值可以调用该调用。正如其他人建议的那样,用括号括起来以创建临时变量仍然可以让您调用匿名函数:

(function sayHello (name) {
   alert("Hello there " + name + "!");
})('Mike');

Edited because my answer had incorrectly read the original post:

As your function is no longer being assigned as a lambda function to a value, invoking the function afterwards with ("Mike") won't work as there's no value to invoke the call on. As others suggested wrapping this with parenthesis to create a temporary variable will still let you invoke the anonymous function:

(function sayHello (name) {
   alert("Hello there " + name + "!");
})('Mike');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文