在 JavaScript 中的回调函数中引用对象

referring to the object in a callback function in javascript

本文关键字:引用 对象 函数 JavaScript 回调      更新时间:2023-09-26

我的指令是:

map.canvas.addEventListener("mousemove", mapOnMouseMove, false);
function mapOnMouseMove (e) {
   // here : this refers to the canvas of the map object
   // i want to refer to the map (is there a way ?)
}

你可以欺骗this像这样引用map

map.canvas.addEventListener("mousemove", canvasOnMouseMove, false);
function canvasOnMouseMove (e) {
   mapOnMouseMove.call(map, e);
}
function mapOnMouseMove (e) {
   // here : this refers to the map object
}

>您可以使用bind创建一个绑定函数(其中 this 的值是您的map对象):

map.canvas.addEventListener("mousemove", mapOnMouseMove.bind(map), false);

但请注意,由于 bind 是 ES5 方法,因此在较旧的浏览器中不受支持。上面链接的 MDN 文章提供了一个您可能也想要使用的填充代码。