简体   繁体   English

(函数fn(){…})()不起作用

[英](function fn(){ … })() not working

I'm trying to incorporate some crazy callback-recursion combo into my Node.js app. 我正在尝试将一些疯狂的回调递归组合添加到我的Node.js应用程序中。 After some research, I found a strange syntax to both declare and execute function in the same block. 经过研究,我发现了一个奇怪的语法可以在同一块中声明和执行函数。 So I try this simple code to test the concept: 因此,我尝试使用以下简单代码来测试概念:

 (function hello() { console.log("Hello, world!"); })(); hello(); 

I expect it to just put two Hello, world! 我希望它能放两个Hello, world! 's in the console. 在控制台中。 One immediately after declaration and one for the hello() call. 声明后立即执行一次,而hello()调用执行一次。 However, it just prints one and then throws an error saying hello is not defined at hello() . 但是,它只打印一个,然后抛出一个错误,提示hello() hello is not defined hello()

Is there something I'm not getting here? 有没有我要来的东西吗?

A named function expression only creates a variable with the same name as itself within its own scope. 命名函数表达式只能自己的作用域内创建一个与自身名称相同的变量。 This is useful if you need to call it recursively. 如果您需要递归调用它,这将很有用。

(function hello() {
    // "hello" exists as a variable only here, inside the function
    console.log("Hello, world!");
})();

You need a function declaration to create a matching variable in the same scope as the function is declared (and you can't immediately invoke a function declaration). 您需要一个函数声明来在与声明函数相同的范围内创建一个匹配变量(并且您不能立即调用函数声明)。

 function hello() { console.log("Hello, world!"); } hello(); hello(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM