javascript - "this" keyword inside closure -
i've seen bunch of examples can't seem sample code work.
take following code:
var test = (function(){ var t = "test"; return { alertt: function(){ alert(t); } } }()); and have function on window.load like:
test.alertt(); that works fine. however, when try explicitly set context of t inside alert() in alertt, undefined.
i've tried:
var = 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 missing? need able set context explicitly things callbacks etc. i've seen examples (http://stackoverflow.com/questions/346015/javascript-closures-and-this-context) seem i'm doing, why not work?
t normal variable in scope of outside anonymous function (and inner anonymous function). isn't property on object, set without reference this, that, or the_other.
var test = (function(){ var t = "test"; return { alertt: function(){ alert(t); }, sett: function (new_value) { t = new_value; } } }()); test.alertt(); test.sett('hello, world'); test.alertt(); the syntax using usual pattern creating acts private variable in js.
Comments
Post a Comment