简体   繁体   English

为什么要执行此功能?

[英]Why is this function executed?

I need help with understanding how the following script is working. 我需要帮助了解以下脚本的工作原理。

var foo = function() {
    console.log("A");
}

(function() {
    // Empty
})

When running this script with node (v5.9.1) the output is "A" . 使用节点(v5.9.1)运行此脚本时, 输出为“A” I would expect it to just do nothing. 我希望它什么都不做。 Why is foo executed here? 为什么在这里执行foo I can either delete the first or last three lines and then there is no output. 我可以删除第一行或最后三行,然后没有输出。

  • Edit: it works as expected if I place a ; 编辑:如果我放置一个;它会按预期工作; after the curly bracket on line 3. But why? 在第3行的花括号之后。但为什么呢?

If you put (...) immediately after a function expression, you execute that function. 如果在函数表达式之后立即放置(...) ,则执行该函数。

The code in the question defines a function which calls console.log . 问题中的代码定义了一个调用console.log的函数。 Then it calls that function (passing it an argument (which isn't used) of a function which does nothing anyway). 然后它调用该函数(传递一个函数的参数(未使用),无论如何都不做任何事情)。 Then it assigns the return value of calling the first function to foo . 然后它将调用第一个函数的返回值赋给foo

It could be rewritten as: 它可以改写为:

var function_a = function() {console.log("A");};
var function_b = function() {};
var foo = function_a(function_b);

… with the only side effects being the creation of the function_a and function_b variables. ...唯一的副作用是创建function_afunction_b变量。


Semi-colon insertion is usually considered harmful because it leads people to expect whitespace to separate the statement into two unrelated expressions. 分号插入通常被认为是有害的,因为它会导致人们期望空格将语句分成两个不相关的表达式。

JSHint would warn you of the problem: JSHint会警告你这个问题:

7 Missing semicolon. 7缺少分号。

JavaScript将(...)解释为对先前定义的函数的调用(请注意,您将另一个函数作为参数传递,在foo中被忽略),因为}(符号之间没有任何内容)。

With your code 用你的代码

var foo = function() {
    console.log("A");
}

(function() {
    // Empty
})

the javascript interpreter is reading this : javascript解释器正在读这个:

var foo = function() {
    console.log("A");
}(function() {});

For the interpreter you declared an anonymous function, and pass it a parameter and it returns nothing, then value of foo is undefined 对于解释器,您声明了一个匿名函数,并传递一个参数并且它什么都不返回,那么foo的值是undefined

That's why it is very important to put ; 这就是为什么放置非常重要的原因; in each end of line when it is neccessary. 在必要时在每一行。

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

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