4 ms·
Nonsense. It's not a question of whether you understand `this` or not, it's a question of whether thinking about the different cases of `this` is really a good
by RSZC 9y ago
Nonsense. It's not a question of whether you understand `this` or not, it's a question of whether thinking about the different cases of `this` is really a good use of your time. Alternately: `this` is poorly designed and gets in your way.
Here's an example of a recent production bug:
async.timeout(server.close, 60000)(exit)
And one way to fix:
async.timeout(cb => server.close(cb), 60000)(exit)
In case the problem is non-obvious (that's the point!), the first line loses the binding to the specific `server` in question. Lovely. `this` in JS forces the consumer of a module (in this case `server`) to have knowledge of how the module represents its state in order to use it. That's not a good pattern.
- lucideer 9y ago> In case the problem is non-obvious (that's the point!), I think what the gp was saying is that the table stakes for JS is this being obvious. I guess whether it is is subjective, but I have to agree. Your example is glaringly obvious to me. Any assignment of a method on an object, or passing of one as an argument (i.e. any passing/assignment that includes a dot before a method) stands out. This doesn't involve any cognitive overhead if you actually know what `this` is. > `this` in JS forces the consumer of a module (in this case `server`) to have knowledge of how the module represents its state in order to use it. No it doesn't... It requires the method to have access to the module it's defined on, which means you can't pass (i.e. reassign) the method on its own. In your example, the module (server) is not being consumed, only one of the modules methods is consumed on its own; the module is left behind and not consumed (i.e. `this` is left behind)
- RSZC 9y agoIt's kind of funny to hear that the example is 'glaringly obvious', given that if the module in question was implemented as a singleton, the first line would be both correct and preferable...
- lucideer 9y agoThe fact that your statement includes a qualifier ("if the module... was implemented as...") means it's never going to be preferable. Nothing should depend on a qualifier that isn't self-evident from syntax. As for what is preferable... const closeServer = () => server.close(); async.timeout(closeServer, 60000)(exit); Abstracting `server.close()` and naming it `closeServer` may seem to be a bit redundant, but the example given was slightly contrived so this would be almost always preferable in practice.