Let me tell you about “this”…

Nitika
Nitika
Jul 28, 2017 · 4 min read

JavaScript has a special keyword: “this.”

It can be difficult to have a verbal conversation about “this” since it can be confusing if I refer to this as a keyword in JavaScript, but it is definitely easier to differentiate “this” and this in the written form.

I’m going to use this space to tell you some important things about this keyword called “this.”

“this” is a context.

When used outside of a function or object, the context of “this” is the global context, or if in a browser it will be the window object. To avoid using the global context or window object accidentally as the “this” context, it is good practice to declare “use strict mode” at the top of your code. This will result in “this” being “undefined” if it is not declared within an object. “Undefined” is easier to catch than information captured from the window object or the global context.

Why is “this” useful?

When constructing an object, you’ll often see the “this” keyword used to define a class whose constructor takes parameters.

class President {
constructor(experience, intelligence) {
this.experience = experience,
this.intelligence = intelligence
}
}

In the example above, when a hopefully high score of experience and intelligence is passed in to create a new instance of President, the instance will take on the “this” context and so the instance will be assigned a property of experience and intelligence that corresponds to the values passed in.

The beauty of “this” is that it can change depending on where you are using it. Instead of referring to the class that created it, it can refer to the instance that is being created.

However, this can create problems when you don’t want the “this” context to change. This hiccup arises when using React components. If you declare a function in a react component, which is a class, and then call it in the the render function, the “this” context will have changed and “this” will become undefined since we are not invoking the function but passing it to a handler function, and then invoking it with the global context:

onChange={this.handleChange}

This brings us to three important functions in JavaScript: bind(), call(), and apply(). These three functions allow us to control the “this” context of a function. We can manipulate what context the function is being invoked on.

With bind(), we can bind the “this” context to a specific context so that it is always called with the same context. This is helpful for our React components and can be helpful for other use cases as well.

class President { 
constructor() {
this.message = "This is not very democratic!"
}
executiveOrder() {
alert(this.message)
}
}
let trump = new Presidentlet trumpAlert = trump.executiveOrder
trumpAlert()

In the example above, we have created a new instance of a President. We then want a separate alert for the trump instance of President that lets this instance know that “This is not very democratic!” maybe because we will want to call on it on other actions, not just executive orders. In the above code, we have created that variable and assigned it the method executiveOrder which is a method on the trump instance of President.

The result of calling trumpAlert() will be an alert with the message undefined. When we call the function trumpAlert() the context of “this” for this.message is the global context and so returns undefined. To solve this and have our trumpAlert() say what we need it to say, “This is not very democratic!”, we will have to bind the “this” context. Since the constructor includes a definition of this.message, the “this” context will then change to the instance of trump. All we need to do now is bind the function to the context of trump.

let trumpAlert = trump.executiveOrder.bind(trump)

Now, whenever we call trumpAlert(), which might have to be many times through the life of the trump instance of President, we will get the message that we want: “This is not very democratic!”

The functions call() and apply() are similar to each other and allow you to change the “this” context of the function that you are calling. The difference between the two is that apply() takes an array of arguments, while call() takes the arguments as separate parameters.

Below is an example where we are just defining the “this” context, but not passing in parameters. Both call() and apply() will return “Hello Senator Gillibrand!”

function callSenator() {
let script = "Hello Senator " + this.lastName + "!"
console.log(script)
}
const nySenator = {
firstName: "Kristen",
lastName: "Gillibrand"
}
callSenator.call(nySenator)
callSenator.apply(nySenator)

For more examples of bind(), call(), and apply() checkout the MDN docs.

I hope this explanation was helpful or at least enjoyable to read. Please leave me comments! 😃

Nitika

Nitika

Teacher, coder, job seeker and lover of comments and discussion, hint, hint.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade