这三种听取事件的方式之间的范围有何不同? [英] How the does scope differ between these three ways of listening for events?
问题描述
假设函数 doSomething()
是在同一个地方定义的,那么执行该函数的范围在这三种侦听事件的方法之间是否有所区别?
Assuming the function doSomething()
is defined in the same place, does the function's scope when it is executed differ between these three methods of listening for events?
<body onload="doSomething();">
document.body.onload = doSomething;
document.body.addEventListener('load', doSomething);
除了属性只能包含一个监听器而不是 addEventListener ()
,在这三种方式中监听事件之间是否存在其他差异? (例如传入参数,或者这个
的值?)
Aside from attributes only being able to contain one "listener" compared to addEventListener()
, are there any other differences between listening for events in these three ways? (such as passed in parameters, or the value of this
?)
推荐答案
onload =doSomething();
类似到
document.body.onload = function(event) {
doSomething();
};
在事件处理程序本身内部,此
是指处理程序绑定到的元素,但在 doSomething
,这个
将引用窗口
,既然你正在调用正常功能。 doSomething
也无法访问事件对象。如果你想要 doSomething
这个和事件
>与其他情况一样:
Inside the event handler itself, this
refers to the element the handler is bound to, but inside doSomething
, this
will refer to window
, since you are calling the function "normally". doSomething
doesn't have access to the event object either. You have to pass this
and event
along if you want doSomething
work the same as in the other cases:
onload="doSomething.call(this, event);"
注意:文件的属性
,祖先DOM元素和DOM元素本身属于事件处理程序 (不是 doSomething
),这可能会导致非常混乱的行为。有关详细信息,请参见我的答案。
Note: Properties of document
, ancestor DOM elements and the DOM element itself are in the scope for the event handler (not doSomething
), which can lead to very confusing behavior. See my answer here for more info.
document.body.onload = doSomething;
和 document.body.addEventListener('load',doSomething);
相当于范围和上下文,它们没有内联事件处理程序具有的这种奇怪的范围行为。
document.body.onload = doSomething;
and document.body.addEventListener('load', doSomething);
are equivalent in terms of scope and context, and they don't have this strange scope behavior that inline event handlers have.
有关不同方式的更多信息,请访问quirksmode.org。
这篇关于这三种听取事件的方式之间的范围有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!