7

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?

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

3

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++;
    });
}

Comments

1

You can write a bind function and bind the context with the 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);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.