我有一个需要在窗口中拖动的元素,具有功能的代码运行良好,但是当我使用类时,我无法理解为什么它不能。
你能帮我manipulate_this_element()
吗?下面的codepen中的方法?
https://codepen.io/igor-sushko/pen/oNNBvQX?editors=1011
class View {
create_staff() {
console.log("staff work!");
this.listener();
};
listener() {
console.log("listener work!");
let a = document.getElementById("AAA");
a.addEventListener("mousedown", this.mouse_down)
// .onmousedown = this.mouse_down();
};
mouse_down(e) {
let that = this;
console.log("mouse_down work!");
e.preventDefault();
document.addEventListener("mousemove", that.manipulate_this_element)
// document.onmousemove = this.manipulate_this_element();
};
manipulate_this_element() {
console.log("manipulate_this_element work!");
};
}
let a = new View();
a.create_staff();
我想看看“manipulate_this_element 工作!”当我移动鼠标时在控制台中
最佳答案
问题是,使用 a.addEventListener("mousedown", this.mouse_down)
时,事件发生时不会在 View 对象上调用 mouse_down
,因此mouse_down
中的 this
不再引用 View 实例。
为了解决这个问题,您可以通过多种方式将 this
绑定(bind)到函数。
鉴于您已经使用了 class
那么您可能已经能够使用以下语法:
mouse_down = (e) => {
}
以这种方式使用箭头函数将会将该箭头函数的 this
绑定(bind)到 View
的实例。
此方法的一大优点是,这还允许您使用 a.removeEventListener("mousedown", this.mouse_down) 轻松删除事件监听器
完整代码如下:
class View {
create_staff() {
console.log("staff work!");
this.listener();
}
listener() {
console.log("listener work!");
let a = document.getElementById("AAA");
a.addEventListener("mousedown", this.mouse_down)
// .onmousedown = this.mouse_down();
}
mouse_down = (e) => {
let that = this;
console.log("mouse_down work!");
e.preventDefault();
document.addEventListener("mousemove", that.manipulate_this_element)
// document.onmousemove = this.manipulate_this_element();
}
manipulate_this_element = () => {
console.log("manipulate_this_element work!");
}
}
let a = new View();
a.create_staff();
关于javascript - 如何调用类中的方法抛出事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58485073/