Probably all React developers will nod knowingly when they see this (but surprisingly, not all of them can articulate what is really happening behind the scenes):
What it means is:
- Each object is actually a property bag—it’s nothing more than a dictionary where the keys are always strings.
- Each object has a “prototype” property, which is a reference to the object it inherits from.
Here’s another example:
In ES5 code, this is equivalent to:
In fact, you could write something like this in ES5:
And yes, it would work because we called the function in the context of the myObj object.
<button onclick="onClick()">Click me!</button>
In this particular case, this will be bound to the Button instance and you would be able to do DOM manipulation in the handler. As you can see in React, you are not always getting a reference to what you expect in this! Luckily we can fix this, because we can actually specify the value this gets.
So in our example, we could do this:
That’s helpful, but we might not always want to pass that this object as a parameter. Isn’t there an easier way? It actually is, we can use bind():
One more thing. You might have seen something like this in old jQuery code:
If you don’t want to use this trick, what you could do is:
We used a lambda or inline function. Keep in mind these have no effect on the this keyword but are an ES6 feature which might not be supported by older browsers. Oh, and ditch jQuery altogether, I was just using it as an example.