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 教程的解释。
setTimeout(foo, 2000)
将函数foo
和数字2000
作为参数传递给setTimeout
. setTimeout(foo(), 2000)
调用foo
并将其返回值和数字传递2000
给setTimeout
.
在第一个示例中,您\xe2\x80\x99根本没有调用该函数,只是将其作为参数传递,就像任何其他值一样。
\n\n作为一个更简单的例子,只需记录它:
\n\nfunction 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
归档时间: |
|
查看次数: |
4609 次 |
最近记录: |