Tip 42: Resolve Context Problems with Bind()
In this tip, you’ll learn how to solve this errors with bind().
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.
Get hands-on with 1400+ tech skills courses.