All we should know about “bind” & “this” in JavaScript & React

Image for post
Image for post

The concept of bind is one thing that bothers interns, to the extent that they may give up learning and use the syntax only. In this article, we’re going to understand all of it at it’s simplest. Then learn the different bind() styles and better understand its usage in the class components.

Let’s start with this simple code snippet:

Image for post
Image for post

The output of this code snippet is 27. So far, so good! But the problem arises when we assign this function to a variable. Think carefully about the output of this code snippet and try to guess the result of it:

Image for post
Image for post

The result is “undefined.” the only difference is we assigned our function to a variable this time.
Suppose this happens:

Image for post
Image for post

Do you know where “this” is pointing? To understand this, I convert this.age to this in the showAge function, from the log. That’s mean:

showAge: function () {
console.log(this); //here this.age was changed to this
}

With this change, in the Node.js, “global” and in the browser environment, “window” will be returned.

Well, so far, it makes sense why “this” returned “undefined”. There’s no such thing as “age” in global(Node.js) and window(browser environment). And “this” when assigned to a variable, no longer points to its object. Now “bind” can help us specify where “this” must point! So our final code looks like this:

Image for post
Image for post

sit tight! we want to go deeper :) Suppose we’ve two objects instead of one userData object. Take a good look at this code:

Image for post
Image for post

So we can easily bind “this” wherever we want.
If you’re careful, I wrote some styles under all the photos. Let’s see what each one means :)

  1. Default Binding

As the name implies, when we don’t bind. And “this” refers to the default. An all-important point that we’ll use it:

If we’re in “strict mode”, the default binding for “this” has an “undefined” value, otherwise, it returns global(Node.js) or window(browser environment).

Mind your eye! the reason why in the class components of React, sometimes “this” will returns “undefined”!

You may ask, well, I don’t use “strict mode”. So why in my class component, “this” is “undefined”?

The point is:

classes’ body executes in “strict mode” automatically!

Its reason is a problem that existed until ECMAscript 262 edition 5, which we won’t review it.
So, in a nutshell:

Default Binding in “strict mode” => undefined

Otherwise => global or window

For more clarity, back to the second and third code snippets of this article (below the photos, there is a number and type of binding, be sure to check it out). Let’s go to the next :)

2. Implicit binding

When “this” refers to somewhere other than the default binding. Now with these types, it is much easier to summarise our discussion:

If we assign an object’s function in the variable, it will change from Implicit Binding to Default Binding.

To understand the above point more precisely, I suggest you check the first Code Snippet once again.

3. Explicit Hard Binding

Combination of types 1 and 2!

When Implicit Binding becomes Default Binding, and we want to bind it to the same object. And the same things we saw above that we “bind” wherever we wanted. Check the fourth and fifth code snippets of this article :)

And what happens in the React class components?

When we should use bind in event handlers؟ Those who didn’t learn the concept find that sometimes it works without a “bind” and sometimes gives an “undefined” error! In this section, I’ll explain all these cases.
Let’s start with this snippet of code. This snippet is familiar to many of us. But do you know why “this” returns “undefined”?

Image for post
Image for post

In the above code snippet, we want to alert a name that comes from component props. And obviously, we need “this” that is implicitly bound(second type) or Explicitly Hard Bound(third type), not default bound(first type).

But the important point is why this function returns “undefined” and “this” is the default bound?

When we use events, the event handler function, which in the above code snippet is alertName, loses its Implicit Binding and returns the Default Binding.

Maybe you can say again, so ok :)) Why does Implicit binding become default binding? I have to answer that you should consider the whole story like this.

let onClick = this.alertName;
onClick();

Suppose we want to look at the issue more technically. In that case, my whole point is assigning an event handler(aleteName here) to the onClick event. It’s just a simulation for better understanding.

So we returned to the first subject of the article, we assigned a function with “this” in a variable. And most of the time, we use the constructor to do the “bind” work, or sometimes we use “bind” to invoke the event handler. And another question that arises:

Why do we do this in the constructor?

We want to continue the example above to get out of the “undefined” value for “this”. This snippet of code is familiar to all of us:

constructor(props) { 
super(props);
this.alertName = this.alertName.bind(this);
}

The console shows us the body of the component(in this example, Login). Now, if we log this.alertName, it will show us the function itself. What we see in the console is:

ƒ alertName() { 
alert(this.props.name);
}

Well, so far, we have our function to the left of this line of code:

this.alertName = this.alertName.bind(this)

And what we’re doing here is Explicit Hard Binding! It means that we “bind” our function body(this.alertName) to our class body(this).

We looked at it very hard, didn’t we? It becomes merely apparent this question for all of us in React.

Hardships are over with Arrow Functions!

Image for post
Image for post

And the last type for bind! So far, we’ve mentioned three kinds of Default Binding, Implicit Binding, and Explicit Hard Binding.

The latest style is using arrow functions:

4. Lexical binding

If we use the Arrow Functions, we no longer need any kind of bind. Because they automatically bind this to the scope that is defined :)))

So now we can understand the reason for “sometimes it works” in React. so we do this:

Image for post
Image for post

Or we can leave onClick intact, but write the top as an Arrow function. That’s mean:

Image for post
Image for post

One of the differences between function and arrow function, which interviewers often asked in their questions, is also highlighted here. Lexical Binding capability!

It wasn’t hard, was it? It’s just an example of all the things we may not have pursued. And maybe one of these things in big projects can cause significant problems and cause trouble in the worst possible cases! I hope you find it useful :)

Good Luck❤Reza Hasani

Written by

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store