Javascript function call with/without parentheses

后端 未结 6 1789
南旧
南旧 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 07:57

    In your question, foo is

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

    whereas foo() is

    console.log(hello world)

    The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds, and this function is supposed to be the first parameter to it, in your first case you are passing a function that is why the behaviour is expected and in the second case you are passing console.log(...) which is not a function, so it is executing foo() first and prints in console hello world then waits for 2 sec and do nothing and thus showing wierd behaviour.

    See

    typeof foo; // is function

    typeof foo(); // prints hello world in console first and then says undefined.

提交回复
热议问题