函数调用和函数引用有什么区别? [英] What is the difference between a function call and function reference?

查看:665
本文介绍了函数调用和函数引用有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下功能:

$ p $ function hello(){
alert(hi!);
}

取这段代码:

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

我的问题可能有点难理解,请耐心等待:
什么是正确的将这段代码与普通调用区分开来,还是让这段代码需要引用函数变量而不是常规调用? ( hello();



如何知道我应该在哪里给出函数的引用,当我应该实际调用它的时候?

解决方案

那么, onclick 属性期望引用一个函数,以便在元素被点击时执行。通常它可以是:

  element.onclick = funcRef; 

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

(但当然,最好使用 addEventListener attachEvent



注意它们都是函数的引用,而不是调用。



当某些事情需要引用时,你不会调用它...你为它分配一个引用(第一个例子)。

当你想专门调用一个函数时,可以用()来调用它(第二个例子)。但请注意,在第二个示例中,仍然有一个对分配给 onclick 的函数的引用 - 它只是一个匿名函数。



可能是更重要的部分:

有些人认为您想这样做:

  element.onclick = funcRef(); 

但是这会立即执行该函数(因为()),并将其返回值分配给 onclick 。除非返回值函数,否则这不是你想要的。



我认为这个故事的寓意是,当你想要/需要一些东西来执行,你可以调用这个函数。如果该功能需要以后使用或需要存储,则不要调用它。


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?

解决方案

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.

这篇关于函数调用和函数引用有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆