How to call JavaScript class instance method from DOM event?

javascript, jquery

Solution

Just run it in an anonymous function to invoke it. Since you're calling a method on the object, you need parenthesis.

$(function(){
    $("#AliceOnClick").on("click", function() {
        alice.SayHi();
    });
    $("#BobOnClick").on("click", function() {
        bob.SayHi();
    });
});

Working Fiddle here.

Problem

I have the following simple JavaScript "class": ``` function Person(params) { this.name = params.name; } Person.prototype.SayHi = function() { alert(this.name + " says hi"); } ``` This works as expected when I run it in place. Running the following code gives me a popup that says "Alice says hi": ``` var alice = new Person({name:"Alice"}); alice.SayHi(); ``` But when I try to assign it to a button event, it won't work: ``` $("#AliceOnClick").on("click", alice.SayHi); $("#BobOnClick").on("click", bob.SayHi); ``` It appears that the `SayHi` function gets called, but the `name` field is null. Minimal working example: http://jsfiddle.net/AKHsc/1/ What am I doing wrong?

Original source