Javascript function call with/without parentheses

后端 未结 6 1772
南旧
南旧 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:03

    The basic difference between foo and foo() is the following:

    function foo() {
       alert("bar");
       return "baz";
    }
    
    console.log(foo); // gives "function"
    console.log(foo());  // gives "baz"
    

    foo is a reference to the function body itself while foo() executes the function. Thus

    setTimeout(foo(), 2000);
    

    passes the return value ("baz") to the function setTimeout(which will result in an error). setTimeout expects an "executable" function as first argument, so you need to pass in a reference to an existing function.

提交回复
热议问题