I use this snippet in Javascript like 100 times a day to have a closure on the enclosing object:
Class.prototype.Method = function(arg){
var Ta = this;
var e = function(){
Ta.doSomething(arg);
};
};
it there a way to avoid the Ta variable and still refere to the “outer” (is this word correct?) object?
a) You could continue using this approach with more meaningful variable names. Using
thatis a common convention — it’s indicative that your variable is just another “this” value, but for another function scope.b) You can use a function bind utility. Some JavaScript libraries come with one. Or you can simply roll your own:
Update:
As @Pointy noted,
bindis actually part of a new version of the JavaScript spec, getting picked up by modern browsers already: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind