4 ms·
> "This" is an ill-defined concept (illustrated by the 3 categories and 5 subcategories of the OP) I would disagree with that. The concept behind "this" is ac
by M1573RMU74710N 15y ago
> "This" is an ill-defined concept (illustrated by the 3 categories and 5 subcategories of the OP)
I would disagree with that.
The concept behind "this" is actually pretty simple and well-defined: it's part of the execution context that every function has in Javascript...and it's behavior is predictable based on a small set of principles outlined in the OP.
What those various examples demonstrate is that it's a dynamic concept (an important distinction imho). It's this property which gives a lot of novice developers trouble, but it's also what makes it extremely powerful.
The "effort" you speak of is the extremely minor effort of remembering how "this" behaves in a given scenario (which again, is basically one of several well-defined possibilities).....as opposed to the effort of coding "around" using "this" which will add just as much complexity to your code overall.
To me your suggestion sounds like saying you should only buy what you can pay for with exact change because it's too much "effort" to do some simple arithmetic each time to determine if you've received the correct change.
That's true of course, but this also hinders you in what you can do, and requires effort itself.
I would say both strategies have their benefits and drawbacks, but are ultimately comparable. You can certainly code "around" the this keyword; for example by using closures to create custom types instead of a constructor...
IMHO, avoiding either strategy is the wrong way to go. What you should do is evaluate each situation and determine which strategy offers the best combination of benefits and drawbacks.
In my example, using a closure might be more expressive in some ways, etc etc... but it consumes more memory, will break the instanceof operator, etc etc. There's always trade-offs.
It may be that most of your JS code doesn't require the use of "this", but if a programmer is not able to understand it and use it effectively when the situation calls for it, they will never be complete as a JS coder.
- gruseom 15y agoOf course I can use it if "the situation calls for it". But that's almost never the case. "This" causes hidden coupling. The difficulty isn't remembering how "this" works (that's an annoyance), it's figuring out how a program that uses it heavily works when all the action-at-a-distance kicks in. There is no intrinsic value in being "complete as a JS coder". JS isn't scripture.