2

I found this browsing:

What is the difference between a function call and function reference?

After reading the answers there, I did't understand the definition and usage for function references and function calls. Then I searched a lot, but it is still unclear where to use what.

Could you help me understand this by pointing out the differences in concept and usage? I want to make this as a reference for future programers.

4

1 回答 1

11

Take this for example:

function foo() {
    alert('foo');
    return 'bar';
}

First of all, what is a function? It's a routine that can be called (or "invoked", or "executed"), and when you do so it usually does something, and returns some value.

So you have a function named foo. You can call it by adding () after its name:

foo();

You can store the return value in a variable, if you assign the result of the invocation to it:

var something = foo();
something === 'bar'; // true

But that's not all you can do with functions in JavaScript. It's a language where functions are first class citizens, so they can be passed around to other functions, and returned from other functions. They can also be stored as variables. For example:

var refToFoo = foo;

Now refToFoo is the same as foo. It's not a copy, it's a reference pointing to the same (internal) function object as foo. So you can use refToFoo just like you would use foo:

var something = refToFoo();
something === 'bar'; // true
refToFoo === foo; // true; they're the same object

Perhaps the most common use to function references is to use them as event listeners:

someElement.onclick = foo;

Note there is no parentheses above. It we used parentheses, foo would be invoked, immediately, and its return value would be assigned to the element's onclick method. Since that function returns a string, nothing would happen if the element were clicked. That's a very common mistake newbies do. Another common one is invoking a function instead of passing a reference to setTimeout:

setTimeout(foo(), 1000); // WRONG - foo is executed immediately

Compare that to:

setTimeout(foo, 1000); // RIGHT - we're passing a reference to the function, 
                       // that will be invoked by the js engine after 1000ms

I hope this helps clarify your doubt.

于 2013-11-01T18:26:25.630 回答