Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to class member within closure

I have a class method and a closure within this method. How I can access to class member from closure?

Person = function(x) {
  this.x = x;
}

Person.prototype = {
   myMethod: function() {
      $('#myBtn').click( function() {
         // how to access to this.x? the this reference points in another context 
      });
   }
}
like image 846
WelcomeTo Avatar asked Dec 16 '22 06:12

WelcomeTo


1 Answers

Use of Function.prototype.bind will help you here

Person = function(x) {
  this.x = x;
}

Person.prototype.myMethod = function() {
  $('#myBtn').click(function() {
    this.x;
  }.bind(this));
};

You can use some better separation of code here too

Person = function(x) {
  this.x = x;
};

Person.prototype.myMethod = function {
  $('#myBtn').click(this.clickHandler.bind(this));
};

Person.prototype.clickHandler = function(event) {
  console.log(this.x);
};

Note if you want to support older browsers, check out es5-shim


EDIT

I'm revisiting this after ~6 months and I would probably write the above code differently. I like the private/public exposure here. Also, no need for any fanciful binds or anything like that ^.^

function Person(x, $button) {

  // private api
  function onClick(event) {
    console.log(x);
  }

  function myMethod() {
    $button.click();
  }

  // exports
  this.x        = x;
  this.myMethod = myMethod;

  // init
  $button.click(onClick);
}

var b = $("#myBtn"),
    p = new Person("foo", b);

p.x;          // "foo"
p.myMethod(); // "foo"
btn.click();  // "foo"
like image 60
Mulan Avatar answered Dec 31 '22 16:12

Mulan