将事件处理程序分配给使用和不使用括号的方法之间的区别 [英] Difference between assigning event handler to method with and without parentheses

查看:118
本文介绍了将事件处理程序分配给使用和不使用括号的方法之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有以下内容:
$ b $ function doStuff(){
// code
}



















$ b $ window.onload = doStuff;



window.onload = doStuff();



这两个语句立即调用​​方法,但是如果我使用第一条语句,我可以将onload作为函数指针指向doStuff,然后再次使用以下方法调用该方法:



onload();



差异,一般来说,这是事件处理程序的所有保证行为吗?

解决方案

您的理解实际上有些欠缺。

  window.onload = doStuff; 

表示当onload事件被触发时,doStuff函数将被调用。

  window.onload = doStuff(); 

表示当达到该行代码时(onload事件被触发之前),执行doStuff并且它的返回结果被分配给onload处理函数。



除非 doStuff 返回一个函数当onload事件被触发时被执行。


Assuming you have the following:

function doStuff() { //code }

What is the the difference between the 2 statements ?

window.onload = doStuff;

window.onload = doStuff();

Both statements immediately called the method, but if I used the first statement, I could treat onload as a function pointer to "doStuff" and just call the method again using:

onload();

Is this the only difference, and in general, is this all guaranteed behavior for event handlers ?

解决方案

You're actually a bit off in your understanding.

window.onload = doStuff;

means that when the onload event is triggered, the doStuff function will be called.

window.onload = doStuff();

means that when that line of code is reached (before the onload event is triggered), doStuff is executed and it's return result is assigned to the onload handler.

You probably want the first one unless doStuff returns a function to be executed when the onload event is triggered.

这篇关于将事件处理程序分配给使用和不使用括号的方法之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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