2

The code is pretty explanatory. What I am doing is wrong. How can I access the a property of the A object in the onclick event of an object declared inside of an A object method?

function A(){
    this.a = 0;
};

A.prototype.myfun= function(){
    var b = document.getElementsByClassName("myclassName");
    b[0].onclick = function(e){
    //How can I get the a property of the A object in here?
        this.a = 1;
    }
};

Could I somehow pass this as an argument like this?

b[0].onclick = function(e, this){
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Vlad Otrocol
  • 2,952
  • 7
  • 33
  • 55
  • possible duplicate of [Accessing class member variables inside an event handler in Javascript](http://stackoverflow.com/questions/3076010/accessing-class-member-variables-inside-an-event-handler-in-javascript) and [Preserve 'this' reference in javascript prototype event handler](http://stackoverflow.com/q/8100469/218196) and [How can I access `this` in an event handler?](http://stackoverflow.com/q/7696672/218196). – Felix Kling Jun 22 '13 at 15:25

1 Answers1

2

Since this in a function references to the function itself, you could do 2 things. Pass around the reference, or create a variable you won't overwrite that represents the this

function A(){
    this.a = 0;
};

A.prototype.myfun= function(){
    var self = this;
    var b = document.getElementsByClassName("myclassName");
    b[0].onclick = function(e){
        self.a = 1;
    }
};
Rene Pot
  • 24,681
  • 7
  • 68
  • 92