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

时间:2012-07-03 08:45:53

标签: javascript events callback

我的指示如下:

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 ?)
}

2 个答案:

答案 0 :(得分:1)

你可以欺骗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
}

答案 1 :(得分:0)

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

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

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