Issam Zoli
Issam Zoli

Reputation: 2774

Access parent's property

Hi I need to change the mousemove property onMouseMove but I can't access the myfunc object because this refer to the el not the parent !!

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

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

Upvotes: 2

Views: 901

Answers (4)

zzzzBov
zzzzBov

Reputation: 179284

Just store a reference to this, call it whatever you'd like. It's common to use that or self:

function myfunc(el) {
  var that;
  that = this;
  this.el = el;
  this.mousemove = false;
  el.mousemove = function () {
    that.mousemove = true;
  };
}

Upvotes: 5

JaredPar
JaredPar

Reputation: 755587

It sounds like you want to change the mousemove value from the onmousemove handler. If so then you need to capture the original context in a value which you can later access. For example

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

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

Upvotes: 1

Naftali
Naftali

Reputation: 146360

Remove the this's because they all refer t window

function myfunc (el) {
  var mousemove = false; //scoped

  el.onmousemove = function(){
      mousemove = true; //same scoped variable
  };
}

Upvotes: 1

Shad
Shad

Reputation: 15471

One approach is to create a reference to the relevant this; e.g.

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

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

Upvotes: 1

Related Questions