I simulated a class in JavaScript; it's code is 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 created an instance of this class and executed it's method init(), but when I click on any div.mybtn element, it did not increment the value of this.count.
It seems the object this was passed to event handler by value not by reference.
How I can pass a variable to an event handler by reference?
You can't increment undefined, you have 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
Javascript doesn't have pass-by-reference parameters. For what you want, you should use a closure variable:
this.init = function(){
    var self = this;
    $("div.mybtn").click(function(){
        self.count++;
    });
}
                        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