I’ve been writing JavaScript for a bit and have now seen code using the idiom
var that = this;
and
var self = this;
Used to gain access to this
through closure scope. At this point var self = this
seems somewhat more common.
My question is which of these two idioms is truly the convention?
Since they do exactly the same thing, are there advantages/disadvantages to either?
5
Update 2018: You should use neither and prefer arrow functions that have lexical this
scoping.
Original:
They are both idiomatic.
An experienced JavaScript programmer will know exactly what’s going on when reading either.
It’s just a variable naming thing – there is no empirical reason to choose one over the other – they function exactly the same and they’re both common in big code bases of common open source libraries.
There is no reason to use one over the either. The important thing is to pick one and stick with it, and when you’re joining a new code base – stick to whichever they were doing.
This related question in StackOverflow notes that self
might have a really minor shortcoming where it refers to window
in some browsers – so instead of getting a ReferenceError you’d get a silent error. However – this should not be the case anyway if you use a linter.