How to pass a variable by reference to an event handler in javascript?

I modeled a class in a java script, it has the code here:

function myclass() { this.count ; this.init = function(){ $("div.mybtn").click({n:this},function(e){ e.data.n.count++; }); } this.getCount = function(){ alert(this.count); } } 

Then I instantiated this class and executed its init() method, but when I click on any div.mybtn element, it did not increment this.count .
This object seems to be passed to the event handler by value not by reference.
How to pass a variable to the event handler by reference? Thanks for any help

+6
source share
3 answers

Javascript has no parameters for passing by reference. What do you want to use the closure variable for:

 this.init = function(){ var self = this; $("div.mybtn").click(function(){ self.count++; }); } 
+2
source

You cannot increase undefined , you need to start somewhere:

 function myclass() { this.count=0; // start counting at zero !!! this.init = function(){ $("div.mybtn").on('click', {n:this},function(e){ e.data.n.count++; e.data.n.getCount(); }); } this.getCount = function(){ console.log(this.count); } } var c = new myclass(); c.init() 

DEMONSTRATION

+4
source

You can write a binding function and associate a context with an event handler.

 Function.prototype.bind = function(){ var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift(); return function(){ fn.apply(object, args.concat(Array.prototype.slice.call(arguments))); } } function myclass() { this.count ; this.clicked = function(){ this.count++; }; this.init = function(){ $("div.mybtn").click(this.clicked.bind(this)); } this.getCount = function(){ alert(this.count); } } 
+1
source

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


All Articles