您好我需要更改onMouseMove上的 mousemove 属性,但我无法访问 myfunc 对象,因为此指的是 el 不是父母!!
function myfunc (el) {
this.el = el;
this.mousemove = false;
el.onmousemove = function(){
this.mousemove = true;
};
}
答案 0 :(得分:5)
只需存储对this
的引用,无论你想要什么,都可以调用它。使用that
或self
:
function myfunc(el) {
var that;
that = this;
this.el = el;
this.mousemove = false;
el.mousemove = function () {
that.mousemove = true;
};
}
答案 1 :(得分:1)
一种方法是创建对相关this
的引用; e.g。
function myfunc (el) {
this.el = el;
this.mousemove = false;
var t=this;
el.onmousemove = function(){
t.mousemove = true;
};
}
答案 2 :(得分:1)
删除this
,因为它们都引用了window
function myfunc (el) {
var mousemove = false; //scoped
el.onmousemove = function(){
mousemove = true; //same scoped variable
};
}
答案 3 :(得分:1)
听起来您想要更改mousemove
处理程序中的onmousemove
值。如果是这样,那么您需要在以后可以访问的值中捕获原始上下文。例如
function myfunc (el) {
this.el = el;
this.mousemove = false;
var self = this;
el.onmousemove = function(){
self.mousemove = true;
};
}