Javascript function call with/without parentheses

后端 未结 6 1778
南旧
南旧 2021-02-11 07:39

code_0:

(calling foo without parentheses)

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

setTimeout(foo, 2000);

This

6条回答
  •  别那么骄傲
    2021-02-11 08:10

    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
    

提交回复
热议问题