2

I want to call a "member" function from a class when an onclick event is fired. The onclick event itself should be bound inside the class. This is what I have:

var MyClass = function()
{
    this.value = 'hello';

    this.update = function()
    {
        console.log(this.value);
        // Do some things with this.value
    };

    $('#button').click(this.update);
};

The browser complaints in the update function that this.value is undefined.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
goocreations
  • 2,938
  • 8
  • 37
  • 59
  • 2
    I'm sure `this` refers to the element which you attached to the event listener in that scope? Why not try `MyClass.update`? – Script47 Aug 07 '15 at 13:30
  • 1
    The onclick event will get executed with the clicked event as context, so you have to bind the handler to your class again. – Shilly Aug 07 '15 at 13:32

2 Answers2

5

In the handler function, this refers to the button on which you have clicked. To circumvent it, you can store the this reference to a local variable, and use that instead. The most common variable name used in this case is either self or that.

var MyClass = function() {
    var self = this;
    self.value = 'hello';
    self.update = function() {
        console.log(self.value);
        // Do some things with self.value
    };
    $('#button').click(self.update);
};

Or as others have mentioned, you can explicitely use MyClass.update.

meskobalazs
  • 15,741
  • 2
  • 40
  • 63
1

this is not referring to MyClass.

var MyClass = function () {
    var _this = this;
    this.value = 'hello';
    this.update = function () {
        alert(_this.value);
        // Do some things with this.value
    }
    this.click = function () {
        $('#button').click(_this.update);
    }

    this.click();
};

var myClassOBJ = new MyClass();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="button">Click Me</div>
ozil
  • 6,930
  • 9
  • 33
  • 56