下面我在Javascript中创建一个对象。在构造函数中,我正在设置一个事件监听器。问题是当事件被触发时,找不到this.prop,并且未定义打印输出。我该如何解决这个问题?
var someObj = function someObj(){
this.prop = 33;
this.mouseMoving = function() { console.log(this.prop);}
document.getElementById("someDiv").addEventListener('mousemove', this.mouseMoving, true);
}
发布于 2018-10-08 10:36:01
javascript内置的Function.prototype.bind()用于此目的 例如:
var someObj = function someObj(){
this.prop = 33;
this.mouseMoving = function() { console.log(this.prop);}
document.getElementById("someDiv").addEventListener('mousemove', this.mouseMoving.bind(this),true);
}
有关bind方法的更多信息,访问:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
另外必须将对象someObj的引用传递给元素并在行中使用该引用:
console.log(this.referenceToObject.prop); //this references the DOM element in an event.
https://stackoverflow.com/questions/-100000827
复制相似问题