0
MyObject = function() {
  this.a = "a";
  this.func = function() {
      this.a = "b";
      console.log(this); 
  }

}
.....
m = new MyObject();
$(li).bind('click',m.func);

I want: this in this.func references on the surrounding MyObject object. I get: this references on <li> (thats what the console logs).

Lokomotywa
  • 2,624
  • 8
  • 44
  • 73

1 Answers1

0

Use Function.prototype.bind(), The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

Note: Wrap li in quotes

var MyObject = function() {
  this.a = "a";
  this.func = function() {
    this.a = "b";
    console.log(this);
  }
}
var m = new MyObject();
$('li').on('click', m.func.bind(m));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<ul>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>
Jed Fox
  • 2,979
  • 5
  • 28
  • 38
Rayon
  • 36,219
  • 4
  • 49
  • 76