带/不带括号的 JavaScript 函数调用

del*_*sin 4 javascript parameter-passing function-calls parentheses

代码_0:

foo不带括号调用)

function foo(){
    console.log('hello world');
}

setTimeout(foo, 2000);
Run Code Online (Sandbox Code Playgroud)

这是如何code_0执行的:

start -> wait for 2 seconds -> 'hello world' displayed -> end
Run Code Online (Sandbox Code Playgroud)

代码_1:

foo用括号调用)

function foo(){
    console.log('hello world');
}

setTimeout(foo(), 2000);
Run Code Online (Sandbox Code Playgroud)

这就是code_1执行的方式:

start -> 'hello world' displayed immediately -> wait for 2 seconds -> end
Run Code Online (Sandbox Code Playgroud)

当我用括号调用函数时,为什么程序的执行会如此不同?其根本机制是什么?

抱歉,如果这个问题太琐碎了。但我找不到任何针对初学者的 javascript 教程的解释。

Ry-*_*Ry- 7

setTimeout(foo, 2000)将函数foo和数字2000作为参数传递给setTimeout. setTimeout(foo(), 2000)调用foo并将其返回值和数字传递2000setTimeout.

\n\n

在第一个示例中,您\xe2\x80\x99根本没有调用该函数,只是将其作为参数传递,就像任何其他值一样。

\n\n

作为一个更简单的例子,只需记录它:

\n\n
function foo() {\n    return 5;\n}\n\nconsole.log(foo);   // console.log is passed a function and prints [Function]\n\nconsole.log(foo()); // foo() is called and returns 5; console.log is passed 5\n                    // and prints 5\n
Run Code Online (Sandbox Code Playgroud)\n