I have this code (JSFiddle)
var OBJ = function(){
var privateVar = 23;
var self = this;
return {
thePrivateVar : function() {
return privateVar;
},
thePrivateVarTimeout : function() {
setTimeout(function() { alert(self.thePrivateVar()); } , 10);
}
}
}();
alert(OBJ.thePrivateVar());
OBJ.thePrivateVarTimeout();
This is an abstraction of a real problem I'm having.
So - I would expect the call to OBJ.thePrivateVarTimeout() to wait 10 and then alert with 23 (which I want it to access through the other exposed method).
However self doesn't seem to be setting correctly. When I am setting self = this it appears that this isn't a reference to the function but a reference to the global object. Why is this?
How can I make the public method thePrivateVarTimeout call the other public method thePrivateVar?