问题描述
为什么我无法在run函数中返回element_id?如果将脚本设置为let self = this; function(){ self.run() }
Why am I unable to return the element_id in the run function? The script works if I set it as let self = this; function(){ self.run() }
不起作用:
class clickin {
constructor(element_id) {
this.element = document.getElementById(element_id);
this.element.addEventListener('click', this.run);
}
run() {
alert('Element id: ' + element_id);
}
}
作品:
class clickin {
constructor(element_id) {
this.element = document.getElementById(element_id);
let self = this;
this.element.addEventListener('click', function(){
self.run();
});
}
run() {
alert('Element id: ' + element_id);
}
}
推荐答案
使用addEventListener对象,您正在设置一个回调函数,该事件将在触发事件时被调用.因此,它在与构造函数不同的上下文中运行.在这种情况下,"caller(this)"对象将发生更改,因此,您上面提到的this.run将不起作用.但是,当您将"clickin"类对象分配给变量"self"时,您可以运行,因为self在回调函数中作为闭包可用,并且在执行事件处理程序时,它可以访问该"clickin"对象.您可能需要更深入地了解以下主题,以便更好地理解.
Using the addEventListener object, you are setting a callback function which will be called when the event is fired. So, it runs in a different context than your constructor function. In that case, the "caller(this)" object changes, and thus, this.run you mentioned above won't work.But, when you assign "clickin" class object to a variable "self", you are able to run because self is available in callback function as a closure, and when event handler executes, it is able to access that "clickin" object.You might want to look deeper into below topics for better understanding.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
https://developer.mozilla.org/en -US/docs/Web/API/EventTarget/addEventListener
这篇关于为什么我不能在addEventListener内调用类函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!