re: Is `this` in Javascript bad? VIEW POST


In javascript, there are no absolutes. Your friend is wrong if they believe a single pattern will always be correct. That being said, some guiding principles can be helpful:

  • this is valuable when you're working with a stateful object. You can ask yourself: is your object an instance of a "superclass", in that other instances of this object may exist and have different states? it's very likely that this is the right tool for the job. In fact, as of es6 the module pattern your friend uses should most likely be refactored to a class.

  • this could be considered dangerous when working with raw objects. If you find yourself using .bind a lot, or if you're calling this from inside a method of a non class-like object (e.g. you would never make more than one of the object/function), consider taking a more functional approach. With new Promises and arrow functions, functional javascript has become a lot more fun and readable.

This argument IMO is generally a hold-over from when javascript didn't have classes, so you had the option of either constructing using the module pattern like your friend, or using a function constructor and appending methods to the function's prototype. Nowadays, we don't have to argue because we have the class keyword.

Is this a minefield of possible mistakes in javascript? Absolutely not. It's part of the language, and gives us important OOP abilities. You should use it when appropriate!

Code of Conduct Report abuse