As I’ve starting working with Javascript, I learned the hard way that when you pass an external event handler (like a timer) a reference to a function in your object, you can’t rely on this. to refer to your object – it will instead refer to the scope of whatever fired the event (in the case of the timer, I think it’s window?).
The work around I saw being used is to create a private / local reference to yourself and use that within the callback logic. For example:
function MyObject() {
var myThis = this;
this.foo = true;
this.callback = function() { return myThis.foo; }
this.interval = 30;
setInterval(function () { myThis.callback(); }, myThis.interval);
}
Is this standard coding practice for situations like this, if not, what is the preferred alternative and why (eg. what are the risks of the above example)?
A modern alternative would be to use
Function.prototype.bind()…The
.bind()method returns a function with thethisvalue bound to first argument you provided (which in this case is the enclosingthisvalue).It avoids the need to reference the desired
thisvalue in a variable of the enclosing variable scope from within the variable scope of a nested function (as shown in your question), providing cleaner code.You can find a compatibility patch that is sufficient for most cases at
MDNfor older implementations.Side note, the question of the value of
thisin JavaScript is not a scope question, but rather a calling context question.