带/不带括号的 Javascript 函数调用 [英] Javascript function call with/without parentheses

查看:75
本文介绍了带/不带括号的 Javascript 函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码_0:

(不带括号调用foo)

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

setTimeout(foo, 2000);

code_0 是这样执行的:

start -> wait for 2 seconds -> 'hello world' displayed -> end

代码_1:

(用括号调用foo)

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

setTimeout(foo(), 2000);

这就是 code_1 的执行方式:

And this is how code_1 was executed:

start -> 'hello world' displayed immediately -> wait for 2 seconds -> end

为什么当我用括号调用函数时,程序的表现会如此不同?底层机制是什么?

Why would the program perform so differently when I called the function with parentheses? What is the underlying mechanism?

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

Sorry if this question is too trivial. But I could't find an explanation on any javascript tutorial for beginners.

推荐答案

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

setTimeout(foo, 2000) passes the function foo and the number 2000 as arguments to setTimeout. setTimeout(foo(), 2000) calls foo and passes its return value and the number 2000 to setTimeout.

在第一个示例中,您根本没有调用该函数,只是将其作为参数传递给任何其他值.

In the first example, you’re not calling the function at all, just passing it as an argument like any other value.

举个简单的例子,记录一下:

As a simpler example, just log it:

function foo() {
    return 5;
}

console.log(foo);   // console.log is passed a function and prints [Function]

console.log(foo()); // foo() is called and returns 5; console.log is passed 5
                    // and prints 5

这篇关于带/不带括号的 Javascript 函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆