In this video, we're going to talk about the last two rules for figuring out what this keyword is referencing. The first one is new binding, and the last one will be the Window binding. You may have seen this before. What we have here is a function.
We have capitalized the first letter to express that this is going to be a constructor function, and that should be called with the new keyword. Let's go ahead and have this function take in a color, a name, and a type. Then what we usually do is just go ahead and add those to this.
For now, you can leave out. This in here is just an object. The new binding rule states that when a function is invoked with the new keyword that this keyword inside that function is bound to the new object being constructed, or this object right here.
The last rule for trying to figure out what this keyword is referencing inside a function is Window binding.
Let's say here we had a say age function just like we had in the last video. All it's going to do is console.log this.age.
If I add a function, what we'd usually do is, if we wanted to call say age in the context of me, we would have to do sayage.call and pass in me.
What happens if we didn't have to do that? What if we just tried to invoke say age and we don't specify what the this keyword is?
We're not using call. There's nothing to the left of the dot, so let's see what happens here. I'm going to command all this stuff out, and I run this. You'll notice I get undefined, because what's happening is if you invoke a function that uses the this keyword but doesn't have anything to the left of the dot, it's not using the new binding, and you're not using call, apply, or bind, then the this keyword is going to default to the Window object.
Now, if I go ahead and try to run say age, what happens is I get an error because strict mode is smart enough to know that, "Hey, you don't want to do what you're doing. You don't want the this key word to be bound to the Window object or to reference the Window object, so I'm not even going to let you do that."
To recap all our rules, we have implicit binding, which is you look to the left of the dot, at call time, explicit binding, which is telling a function what the context of the this keyword is going to be using call, apply, or bind.
The new binding is whenever you have a function invoked with the new keyword, the this keyword is bound to the new object being constructed. Then the Window binding where if none of these rules apply, then the this keyword is going to default to the Window object unless you're in strict mode. Then it's just going to be undefined.