1

Suppose, we have the following code:

HTML:

<input type="button" id="button" value="Say hello">

Javascript:

function test ()
{
    this.message = "hello";
    this.on_change = function (){
        alert(this.message);
    }

    this.on_change();
}

$(document).ready(function() {
    var my_object = new test();
    $('#button').click(my_object.on_change);
});

my_object must print "Hello" in 2 cases:

  1. When the instance is created (works)
  2. When clicking the button "Say hello" (doesn't work)

In the second case it prints "Undefined", because this refers to "button" object, and not to the instance of test class.

jsfiddle

user4035
  • 22,508
  • 11
  • 59
  • 94
  • Create a context of `this`: http://jsfiddle.net/s81v1s8h/1/ – tymeJV Sep 29 '14 at 15:49
  • 1). `$('#button').click($.proxy(my_object.on_change, my_object));` 2). `$('#button').click(my_object.on_change.bind(my_object));` 3). `$('#button').click(function() { my_object.on_change(); });` – dfsq Sep 29 '14 at 15:56

2 Answers2

0

Try to remember context of this to some variable:

var self = this;
this.message = "hello";
...

jsFiddle

antyrat
  • 27,479
  • 9
  • 75
  • 76
0

Seems like one of those cases where you should actually create a function for your handler. :)

$(document).ready(function() {
    var my_object = new test();
    $('#button').click(function(){
        my_object.on_change();
    });
});
Scimonster
  • 32,893
  • 9
  • 77
  • 89