Lately I’ve been trying to make an object in JavaScript with the following structure:
function colorDiv(div){
this.div=div;
this.div.bind("click",this.changeColor)
this.changeColor(){
this.div.css("background", "#FF0000");
}
}
The problem is that the changeColor method cannot be called from the jQuery environment because this must refer to the current colorDiv object, so the bind method cannot work as expected.
How can this be solved?
There are a couple ways. The simplest is as follows:
You save a reference to
thisin the variablethat, which is just the name commonly used in the JavaScript world for exactly this purpose. Then you refer tothatinstead ofthisinside yourchangeColormethod. (Note that I usedthateverywhere, just for consistency, even though the only place it actually makes a difference is inside thechangeColormethod.)Another is to use the
Function#bindmethod. You can either use it every time you callchangeColor, like so:or you can use it in the
ColorDivclass to ensure that all methods are bound correctly whenever they are called:As noted in the linked article,
Function#bindis not supported in all browsers, so you’ll need a shim like the one they give, or possibly a full-fledged ES5 shim.Underscore.js has a bindAll function that could be useful here, too, especially with multiple methods:
Finally, it’s worth noting you don’t really need to do any of this in your particular example: just do
instead of what you have, i.e. reference the
divvariable passed in, instead of the reference stored inthis.div, since they are the same thing.