[英]How this object work on addEventListener method in following code?
I have following Html code :我有以下 Html 代码:
<table id="outside">
<tr><td id="t1">one</td></tr>
<tr><td id="t2">two</td></tr>
</table>
and Js code :和 Js 代码:
var el = document.getElementById("outside");
var Something = function(element) {
this.name = 'Something Good';
this.onclick1 = function(event) {
console.log(this.name); // undefined, as this is the element
};
this.onclick2 = function(event) {
console.log(this.name); // 'Something Good'
};
el.addEventListener('click', this.onclick1, false);
el.addEventListener('click', this.onclick2.bind(this), false);
}
Something();
while execution of Something()
, this
refer to the Window
object.在执行Something()
, this
指的是Window
对象。 so onclick1
and onclick2
is the method on Window
object.所以onclick1
和onclick2
是Window
对象上的方法。
Doubt :怀疑 :
el.addEventListener('click', this.onclick1, false);
当el.addEventListener('click', this.onclick1, false);
is executed this
object in this.onclick1
refer to the el
object.执行this
对象在this.onclick1
引用el
对象。 then why onclick1
method is called(which is a method of window
object), when an event is triggred.那么为什么在onclick1
事件时调用onclick1
方法(这是一个window
对象的方法)。 onclick1
method should call on window
object not on el
object. onclick1
方法应该调用window
对象而不是el
对象。el.addEventListener('click', this.onclick2.bind(this), false);
在el.addEventListener('click', this.onclick2.bind(this), false);
How this
object in this.onclick2
and onclick2.bind(this)
is different? this.onclick2
和onclick2.bind(this)
this
对象this.onclick2
不同?Event handlers are passed the element of the event target as the this
object.事件处理程序将事件目标的元素作为this
对象传递。
Function.bind()
forces the this
object of the called function to be a particular object, the parameter to bind. Function.bind()
强制被调用函数的this
对象成为特定对象,即要绑定的参数。
If you don't override this
with fn.bind(thisObject)
when you create the handler function, then it will default to the event target (as mentioned in the MDN link in your question).如果不重写this
与fn.bind(thisObject)
当您创建处理函数,然后它会默认为活动对象(如你的问题在MDN链接提到)。 If you do, it will be whichever object you specified as a parameter to .bind()
.如果这样做,它将是您指定为.bind()
参数的任何对象。
Additional info about .bind()
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind关于.bind()
其他信息: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.