Explicit binding of the "this" keyword

Share this video with your friends

Send Tweet

As one of the most commonly asked interview questions, "What is the this keyword"? This lesson focuses on how you can explicitly bind the context of your function to a specific object. Thus making it obvious what the "this" context will be.

We review the call, apply, and bind prototype method and work to understand how they bind the "this" context explicitly.

Patrick Powers
Patrick Powers
~ 5 years ago

What's a common, good use case for explicitly binding this to a different scope? Is it considered an edge case or behavior? It seems like it would just lead to confusion as opposed to making sure that the this you're working with actually inside the scope it's supposed to be in.

Zac Jones
Zac Jones
~ 5 years ago

What's a common, good use case for explicitly binding this to a different scope? Is it considered an edge case or behavior? It seems like it would just lead to confusion as opposed to making sure that the this you're working with actually inside the scope it's supposed to be in.

@Patrick, a practical use-case I've seen for explicitly binding this is event handlers in React when Class components where more mainstream. This article breaks it down well: bind event handlers in Class Components in React

Jules Randolph
Jules Randolph
~ 5 years ago

I wonder how the defined function context becomes the created object. I have tried to dig in Ecmascript 2015 specs, but couldn't find an answer. I bet the function is bound to the created object:

function getName() {
    return this.name;
}

const fromPerson = Object.create({ name: 'Tyler' }, {
    getName: {
        value: getName
    }
});

person.getName === getName; // false
person.getName(); // Tyler
Tony Brown
Tony Brown
~ 4 years ago

How would you clear the setInterval like this?

Lucas Minter
Lucas Minter
~ 4 years ago

How would you clear the setInterval like this?

The way that I did this was setting your interval to a variable and calling that variable inside of clearInterval.

const person = {
  firstName: "tyler"
};

function getName2() {
  console.log(`${this.firstName} is my first name.`);
}

let myVar = window.setInterval(getName2.bind(person), 1000);

clearInterval(myVar);

This will stop your interval from running. You can set conditions on it so that it'll run a few times then clearInterval will get called. As it is right now in my code, it automatically clears the interval so it doesn't even run once.