访问父母的财产

时间:2011-11-09 21:18:29

标签: javascript oop

您好我需要更改onMouseMove上的 mousemove 属性,但我无法访问 myfunc 对象,因为指的是 el 不是父母!!

function myfunc (el) {
  this.el  = el;
  this.mousemove = false;

  el.onmousemove = function(){
      this.mousemove = true;
  };
}

4 个答案:

答案 0 :(得分:5)

只需存储对this的引用,无论你想要什么,都可以调用它。使用thatself

是很常见的
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;
  };
}