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?
jQuery sets the receiver of the event handler to the target element, so that you can conveniently do something like $(this).hide()
.
You can use e.g. $.proxy
to work around it:
$(function(){
$("#AliceOnClick").on("click", $.proxy(alice.SayHi, alice));
$("#BobOnClick").on("click", $.proxy(bob.SayHi, bob));
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With