Tip 42: Resolve Context Problems with Bind()
Understand how to resolve context problems in JavaScript, especially within classes, by using the bind() method. This lesson helps you control the this keyword in callbacks and class methods, preventing unexpected behaviors. You’ll explore the choice between arrow functions and bind for context management and learn best practices for cleaner, more predictable code.
We'll cover the following...
Preventing context problems
In Tip 36, Prevent Context Confusion with Arrow Functions, you
saw how functions create a new context and how a new context can give you
results you aren’t expecting. Changing context can create confusion, particularly when you’re using the this keyword in callbacks or array methods.
Sadly, the problem doesn’t go away in classes. Earlier, you learned how you can use arrow functions to create another function without a new context. In this tip, you’ll learn more techniques for preventing context problems. The techniques you’re about to learn work on object literals and classes, but they’re much more common in class syntax, particularly if you’re using libraries such at React or Angular.
Think back to the original example, a validator. Originally, you made it as an
object literal, but now that you know a bit about classes, you can make it a
class. The class will have one property, a message, and two methods: setInvalidMessage(), which returns a single invalid message for a field, and setInvalidMessages(), which maps an array of fields to a series of invalid messages.
All you did was translate an object with properties and methods to a class with properties and methods.
The Validator class will have the exact same context ...