I've seen a bunch of examples but can't seem to get some sample code to work.
Take the following code:
var test = (function(){
var t = "test";
return {
alertT: function(){
alert(t);
}
}
}());
and I have a function on window.load like:
test.alertT();
That all works fine. However, when I try to explicitly set the context of t inside the alert() in alertT, I just get undefined.
I've tried:
var that = this;
alert(that.t); //undefined
I've tried:
return {
that: this,
alertT: function(){
alert(that.t); // undefined!
}
}
and I've tried:
var test = (function(){
var t = "test";
var myObj = this;
return {
alertT: function(){
alert(myObj.t); // undefined!
}
}
}());
what am I missing? I need to be able to set the context explicitly for things like callbacks etc. I've seen examples too (http://stackoverflow.com/questions/346015/javascript-closures-and-this-context) that seem like what I'm doing, so why does this not work?