1

Lets assume that i have something like this

function x(a,b,c){
 this.a = a;
 this.b = b;
 this.c = c;
}

x.prototype.z = function(){
 var ele = document.createElement("a");
 a.onclick = this.y;
}

x.prototype.y = function(){
 // How can i use access to a,b,c?
 // If i use this.a, this.b or this.c it wont work because this is 
 //referencing "ele".
}

So my question is.. how can i access to a,b,c variables on the y function after i define it as some element onclick event?

--------- My Solution --------

After some thinking and white paper stratch, i got this by using .bind() as Denys Séguret said and i used event.target to keep with "a".

function x(a,b,c){
 this.a = a;
 this.b = b;
 this.c = c;
}

x.prototype.z = function(){
 var ele = document.createElement("a");
 a.onclick = this.y.bind(this);
}

x.prototype.y = function(event){
   var clickSource = event.target;
   var objectBridge = this;
}
r1do
  • 41
  • 3

1 Answers1

0

You have to bind the function to ensure the context is the right one when the callback is called:

a.onclick = this.y.bind(this);
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758