I’ve come across this problem a few times, and I’m wondering if it can be solved without having to bind the anon function to ‘this’ in the context of the parent object.
Here is my situation:
I have an array-like object, lets call it ‘numline’, which implements an ‘each’ method. It is contained within another instance of an object, lets call it ‘numtank’. The current code looks something like this:
function Numtank(numline) {
this.numline = numline;
};
Numtank.prototype.charForElem(elem) {
return "Number: " + elem;
}
Numtank.prototype.toString() {
var str = "";
this.numline.each(function(elem) {
str += this.charForElem(elem); //But 'this' is called in the contex of the 'numline' instance, which dosen't (and shouldn't) have the charForElem class.
});
return str;
}
var tank = new Numtank(arbatraryNumline);
tank.toString(); //Uncaught ReferenceError: charFromElem is not defined in numline
When I ask ‘similar to how Java does it’, I mean how Java allows you to prepend the class name to ‘this’ to specify which ‘this’ to use.
Is there anyway to get around this without having to bind the anonomouns function to this?
What is generally done is to hold a reference called
self. It is the most common practice.