Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
92 views
in Technique[技术] by (71.8m points)

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

I have the following function

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

Take this piece of code:

var elem = document.getElementById("btn");
elem.onclick = hello;

My question might be a bit hard to understand, so bear with me: What EXACTLY differentiates THIS piece of code from a normal call, or what makes this piece of code require a reference to the function variable rather than a regular call? (hello();)

How can I know where I'm supposed to give a reference to the function, and when I'm supposed to actually call it?

question from:https://stackoverflow.com/questions/65873444/allocating-a-function-name-to-a-variable-v-s-allocating-a-function-to-a-variable

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...