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

前端 未结 6 2484
别跟我提以往
别跟我提以往 2020-11-22 05:50

I have the following function

function hello() {
 alert(\"hi!\");
}

Take this piece of code:

var elem = document.getElem         


        
6条回答
  •  野的像风
    2020-11-22 06:16

    Well, the onclick property expects a reference to a function, for it to execute when the element is clicked. Normally it's either:

    element.onclick = funcRef;
    

    or

    element.onclick = function () {
        funcRef();
    };
    

    (but of course, it's best to use addEventListener and attachEvent)

    Notice how both of them are references to functions, not calling.

    When something expects a reference, you don't call it...you assign a reference to it (first example).

    When you want to specifically call a function, you call it with () (second example). But notice how in the second example, there's still a reference to a function that's assigned to onclick - it's just an anonymous function.

    Probably the more important part:

    Some people think you want to do this:

    element.onclick = funcRef();
    

    But that immediately executes the function (because of the ()), and assigns its return value to onclick. Unless the return value is a function, this isn't what you want.

    I think the moral of the story is that when you want/need something to execute right now, you call the function. If the function is wanted for later use or needs stored, you don't call it.

提交回复
热议问题