Notes of Maks Nemisj

Experiments with JavaScript

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 () {
}, 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.

One thought on “Why I stopped using self when caching ‘this’

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.