0

please refer to the following code,

var XClass = function () {
    this.dataMember = "hello world";

    $("div").on("click", "button", function() {
        console.log(this.dataMember);   //error 
    });  

}

How do I access this.dataMember in on function? I googled and new on js.

CCC
  • 2,164
  • 8
  • 27
  • 47
  • I think this is a better duplicate: [How to access the correct `this` / context inside a callback?](http://stackoverflow.com/q/20279484/218196) – Felix Kling Mar 20 '15 at 08:14

3 Answers3

3

Try by assigning this to a variable:

var XClass = function () {
    var that = this;
    this.dataMember = "hello world";

    $("div").on("click", "button", function() {
        console.log(that.dataMember); 
    });  
}

This way, that will refer to the current XClass object. Otherwise, inside a event handler callback, this refers to the object being clicked.

xlecoustillier
  • 16,183
  • 14
  • 60
  • 85
1

Use bind to set context

var XClass = function () {
    this.dataMember = "hello world";

    $("div").on("click", "button", function() {
        console.log(this.dataMember);   //error 
    }.bind(this));  
}
Evgeniy
  • 2,915
  • 3
  • 21
  • 35
1

Assign this to a variable:

var XClass = function () {
    var self = this;
    this.dataMember = "hello world";

    $("div").on("click", "button", function() {
        console.log(self.dataMember);   // no error 
    });  
}
Chris Ledet
  • 11,458
  • 7
  • 39
  • 47