Javascript function call with/without parentheses

你离开我真会死。 提交于 2020-01-22 13:03:46

问题


code_0:

(calling foo without parentheses)

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

setTimeout(foo, 2000);

This is how code_0 was executed:

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

code_1:

(calling foo with parentheses)

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

setTimeout(foo(), 2000);

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?

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


回答1:


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



回答2:


In the first code snippet, the function foo is being passed to the timeout. That means that foo gets called after 2 seconds when the timeout expires.

In the second code snippet, the function foo is being called to decide what to pass to the timeout. So foo gets called before the timeout is set. Since foo() doesn't return anything, nothing happens when the timeout expires.




回答3:


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.




回答4:


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.




回答5:


The point of confusion here is that you're not realizing that using foo without parentheses is not calling the function...it's only referencing it.

foo is the reference to the function itself. To call a function (i.e. actually execute its code) you reference it with parentheses at the end (e.g. foo()). In a practical sense that means:

// references the function itself
// ...you could call one() now and it would run the function foo
var one = foo;

// runs/calls the function, and var two will then be whatever foo returns
var two = foo();

So in the first example you are NOT calling the function. You are passing the function foo to setTimeout. setTimeout will then call it after a delay.

In the second example you called foo immediately and passed whatever foo returns to setTimeout (which setTimeout couldn't do anything with, because that return value likely wasn't another function). So your function was executed immediately and then nothing would have happened (except likely some errors) after setTimeout was done with its delay.




回答6:


Here's an easy solution. You can use parentheses and pass data to the function if needed.

<script> function foo(){alert("hello world")} setTimeout(function() {foo()}, 2000) </script>



来源:https://stackoverflow.com/questions/34563330/javascript-function-call-with-without-parentheses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!