2 ms·
In JavaScript, "this" is not a variable, or a binding in the local scope. It is a keyword, so it is magic. It was a terribly idiotic design decision, because th
by DonHopkins 13y ago
In JavaScript, "this" is not a variable, or a binding in the local scope. It is a keyword, so it is magic. It was a terribly idiotic design decision, because the variable you'd want to close over most of the time is "this", but since it's not a variable, you can't close over it -- it's dynamically bound, in a really stupid way.
It's the cause of a lion's share of JavaScript bugs. No matter how well you know JavaScript, and how pedantically you understand how "this" works and why it's such a terrible design flaw, you will ALWAYS make mistakes with it, and you will ALWAYS have to go carefully over your code line by line looking for misuses of "this".
Whenever your JavaScript program is misbehaving, the first thing you should do is to search the relevant code for "this", and think carefully about how it might be bound. And even if your JavaScript program is not misbehaving in a way you can detect, you should still do that anyway, because it might just have some very subtle bugs caused by "this".
I've been writing code that starts out with "var self = this;" and then ONLY using "self" and NEVER using "this" except for the first line of a function that goes "var self = this;". That way there's a lot less chance of making mistakes, although it's still possible for that first "this" to be incorrectly bound -- you only want to do the "var self = this;" in top level functions, and all functions contained in them should use self and never use "this".