I'm trying to access a class instance from a callback within a member function. This is one example how it could look like:
MyClass.prototype.foo = function(){
var arr = [1, 2, 3];
arr.forEach(function(element){
//The next line doesn't work
//becuase this doesn't reference my MyClass-instance anymore
this.elements.push(element);
});
}
Here of course I could work with a for Loop (for(var i = 0; i < arr.length; i++) {...}
) but there are situations where I can't.
I found one way to access my MyClass
instance:
MyClass.prototype.foo = function(){
var arr = [1, 2, 3];
var myCurrentInstance = this; //Store temporary reference
arr.forEach(function(element){
//Here it works because I use the temporary reference
myCurrentInstance.elements.push(element);
});
}
This doesn't seem very clean to me. Is there a better way?