How to call an instance method of a JavaScript class from a DOM event?

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. Executing 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, this will not work:

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

It seems that the SayHi function is SayHi called, but the name field is null.

Minimum working example:

http://jsfiddle.net/AKHsc/1/

What am I doing wrong?

+4
source share
3 answers

Just run it in an anonymous function to call it. Since you are calling an object method, you need parentheses.

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

We work Fiddle here.

+5
source

jQuery sets the event handler receiver to the target element, so you can conveniently do something like $(this).hide() .

You can use for example. $.proxy to get around it:

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

So you are calling the function without calling it through instance , and javascript does not support the connection between the instance object and the functions, just pass the instance object to the function.

 function Person(params) { this.name = params.name; } // version 1 Person.prototype.SayHi = function(who) { return function() { alert(who.name + " says hi"); } } // version 2, with `bind` method supported Person.prototype.SayHi = function () { return function () { alert(this.name + " says hi"); }.bind(this); } // version 3 Person.prototype.SayHi = function () { var who = this; return function () { alert(who.name + " says hi"); } } alice = new Person({ name: "Alice" }); bob = new Person({ name: "Bob" }); $(function(){ $("#AliceOnClick").on("click", alice.SayHi())); $("#BobOnClick").on("click", bob.SayHi()); // $("#AliceOnClick").on("click", alice.SayHi(alice)); //$("#BobOnClick").on("click", bob.SayHi(bob)); }); 
+1
source

Source: https://habr.com/ru/post/1494798/


All Articles