I had a “class” defined and was making only one instance of it. The instance possessed a member function that would end up being passed around (it’s a mouse handler, but that’s not important). Since I would only ever make one instance of my “class”, I decided to rewrite it as a singleton by using an object literal.
So I have
var mySingleton = {
theObjects : [];
}
mySingleton.mouseHandler = (function() {
var that = this;
return function (e) {
for (var indx = 0; indx < that.theObjects.length; indx++) {
// do something to that.theObjects[indx];
}
}
}());
mySingleton.addObject = function(newObj) {
this.theObjects.push(newObj);
}
However, when I try to use this code (after adding a few objects), I keep getting an that.theObjects is undefined error. It’s referring to the line in the for loop.
Update for 2015 – Use
Function.bind()to specify the value ofthiswithin the function. Then, instead of usingthat, you can usethis.This doesn’t work if you want
mouseHandlerto have the context of the ‘moused’ element. For that, use my original answer below.If you need to support IE8 or (heaven forbid) earlier, you’ll need to use a polyfill.
Since you are calling the function that creates
mouseHandlerimmediately, it is run in the context ofwindow, notmySingleton. Sothatrefers towindow. Instead of calling it immediately, just change it to a method so that it runs in the context ofmySingleton:Of course, since you are already using a singleton, you can just reference it directly. In your click handler, instead of checking
that.theObjects, checkmySingleton.theObjects. Or, inmouseHandlerchangevar that = thistovar that = mySingleton.Edit: Or, pass the context to your anonymous function when you call it: