|
|
|
|
|
by WilliamLP
5775 days ago
|
|
From the Google style guide: "The semantics of this can be tricky. At times it refers to the global object (in most places), the scope of the caller (in eval), a node in the DOM tree (when attached using an event handler HTML attribute), a newly created object (in a constructor), or some other object (if function was call()ed or apply()ed)." The pragmatic answer is to limit its use except when absolutely required (as Google's guide suggests). The more problematic meta-problem, is that many people do think it's valuable and don't understand it and dig themselves into some subtle and insidious messes. |
|
I've seen JS code that tries to avoid using 'this', and it often ends up a lot more complicated and tightly coupled than code which uses it appropriately.
The behaviour of 'this' in JavaScript is different to Java and other OO languages, but it isn't that complicated to understand.