0

It is duplicate of How to access the correct `this` context inside a callback?, but I was unable to find it here according to my problem description. A lot of people could have the same issue.

I have an object like:

var my_object = new function() {

    this.function2 = function() {
        $("#button").click(function() {
           this.function1()
        })
    };

    this.function1 = function() {
    };

}

a = my_object()

If I click the #button this happen

this.function1 is not a function

How to correctly solve this issue? How to prevent jquery from overwriting my "this"?

Community
  • 1
  • 1
matousc
  • 3,698
  • 10
  • 40
  • 65

2 Answers2

1

When you bind an event handler in jQuery, this inside the callback refers to the element the event has been fired on.

To set the value of this in a function, call bind on the function, passing the object you would like to become this:

var my_object = new function() {

  this.function2 = function() {
      $("#button").click(function() {
         this.function1()
      }.bind(this)
  });

  this.function1 = function() {
  };

}
DinoMyte
  • 8,737
  • 1
  • 19
  • 26
Brennan
  • 5,632
  • 2
  • 17
  • 24
1

Store a reference to this to avoid confusion and context problems.

Within the event handler this is something completely different .. it is a dom node

var my_object = new function() {
    var self = this; // reference to `my_object`

    self.function2 = function() {
        $("#button").click(function() {
           // "this" is dom element returned by jQuery event handler
           // but "self" is already a stored reference to `my_object`
           self.function1()
           $(this).css('color','red')
        })
    };

    self.function1 = function() {
    };

}
charlietfl
  • 170,828
  • 13
  • 121
  • 150