20 02 2013
Why I stopped using self when caching ‘this’
I bet you know the technique of caching “this” scope in order to use it in a closure.
var self = this; setTimeout(function () { self.doSomething(); }, 100);
Of course it’s not a nice way of writing your code, but sometimes it’s just a fast shortcut, especially if you’re working with an older browser which doesn’t support “bind” feature.
Nevertheless, even when I do use it I stopped using “self” as a variable name for “this” cache. Anything else _this, that, This, whatever_cache_name, but NO self.
And a reason is very simple. self is always available at run-time, even if you move your code or refactor it. It will be always a defined variable, no matter what, leaving you without a nice error like “ReferenceError: self is not defined”. Meaning that forgotten `var self = this` will be sitting as a spy in your code till the last moment before it will break.
Why isNaN and Number is not enough to cast string to a number Some interesting aspects of “call” method in JavaScript
Or you use:
.bind(this)
.call(this)
so this actually just stays as this