The `this` Keyword
this
in Constructor Functions
In the previous section, we sawthis
right inside a constructor function. Here's another example:
function Cat(name) {
this.name = name;
this.sayName = function () {
console.log(`Meow! My name is ${this.name}`);
};
}
const bailey = new Cat('Bailey');
In the aboveCat()
constructor, the function thatsayName
points to referencesthis.name
. Back in Lesson 1, we sawthis
used in methods. But inCat()
's case, what exactly doesthis
refer to?
As it turns out, when invoking a constructor function with thenew
operator,this
gets set to the newly-created object! Let's check out what the newbailey
object looks like:
{
name: 'Bailey',
sayName: function () {
console.log(`Meow! My name is ${this.name}`);
}
}
In the snippet above, notice thatthis
is _outside _a constructor function (i.e., in a method). As we saw in Lesson 1, when you saythis
in a method, what you're really saying is "this object" or "the object at hand." As a result, thesayName()
method can usethis
to access thename
property of that object! This makes the following method call possible:
bailey.sayName();
// 'Meow! My name is Bailey'
Note: For a refresher on how a method usesthis
to access an object on which it was called, feel free to review Invoking Object Methods in Lesson 1.
When is
this
Assigned?A common misconception is that
this
refers to the object where it is defined. This is not the case!The value of
this
is actually not assigned to anything until an object calls the method wherethis
is used. In other words, the value assigned tothis
is based on the object that invokes the method wherethis
is defined. Let's look at an example:
const dog = { bark: function () { console.log('Woof!'); }, barkTwice: function () { this.bark(); this.bark(); } };
Let's go ahead and invoke both of
dog
's methods:
dog.bark(); // Woof! dog.barkTwice(); // Woof! // Woof!
We know that when we call
dog.bark();
(ordog.barkTwice();
) a variablethis
gets set. Sincethis
can access the object it was called on,barkTwice
can usethis
to access thedog
object, which contains thebark
method.But what if we just wrote
bark();
instead ofthis.bark();
inbarkTwice
? The function would have first looked for a local variable namedbark
in the scope ofbarkTwice
. Ifbark
isn't found, it would have looked further up the scope chain.To tie things all together:
this.bark();
tellsbarkTwice
to look atdog
-- the object that the method was called on -- to findbark
.
QUESTION 1 OF 4
Time for a quick review! We explored thethis
keyword a bit in Lesson 1, so let's make sure we're on the same page before continuing.
What is true aboutthis
? Select all that apply:
this
refers to "this property," or "this method"Using
this
, methods can access and manipulate an object's propertiesThe exact value ofthis
is already set before a method is invokedthis
is a reserved word in JavaScript
SUBMIT: A value for this
is set when a method is invoked on an object, and that value refers to that object. Since it is a reserved word, it should not be used as any variable name, function name, etc.
QUESTION 2 OF 4
Consider the following constructor function,City
:
function City(name, population) {
this.name = name;
this.population = population;
this.identify = function () {
console.log(`${this.name}'s population is ${this.population}.`);
};
}
The following is executed:
const sanFrancisco = new City('San Francisco', 870000);
What is the value ofthis
?
City
Any property (such asname
, orpopulation
)undefined
, becausethis
must always be inside anobject(i.e., in a method), not a constructor functionThe newly-created object, referenced by
sanFrancisco
SUBMIT: Depending on how a function is invoked, the value of this
is set to a different value. We'll take a deeper dive on this very shortly!
What Doesthis
Get Set To?
At this point, we've seenthis
in many different contexts, such as within a method, or referenced by a constructor function. Let's now organize our thoughts and bring it all together!
There are four ways to call functions, and each way setsthis
differently.
First, calling a constructor function with thenew
keyword setsthis
to a newly-created object. Recall that creating an instance ofCat
earlier had setthis
to the newbailey
object.
On the other hand, calling a function that belongs to an object (i.e., a method) setsthis
to the object itself. Recall that earlier, thedog
object'sbarkTwice()
method was able to access properties ofdog
itself.
Third, calling a function on its own (i.e., simply invoking a regular function) will setthis
towindow
, which is the global object if the host environment is the browser.
function funFunction() {
return this;
}
funFunction();
// (returns the global object, `window`)
The fourth way to call functions allows us to setthis
ourselves! Don't worry about this approach for now; we'll take a deep dive in the very next section.
Whew -- that was a lot ofthis
! Let's compartmentalize these findings in the video below:
QUESTION 3 OF 4
Consider the following object,building
:
const building = {
floor: 5,
addFloor: function() {
this.floor += 1;
}
};
building.addFloor();
//???
What is the value ofthis
whenbuilding.addFloor();
is executed?
window
building
undefined
addFloor()
will return an error becausethis.floors += 1;
cannot be resolved
SUBMIT: Recall that a method can directly access the object on which it was called. In this case, it modifies building
's floors
property by incrementing its value by 1.
QUESTION 4 OF 4
Consider the following:
function myFunction() {
console.log("What is the value of 'this'?");
}
myFunction();
// ???
WhenmyFunction();
is executed, what is the value of thethis
keyword?
myFunction
undefined
this
does not get set to any value when a function is invokedwindow
SUBMIT: When a function is invoked (i.e., as a function, rather than as a method or with the new
operator), this
gets set to the global object: window
. This should be review from Lesson 1, but it's still important to note here as well!
Summary
Functions, objects, andthis
are all interconnected. When invoking constructor functions with thenew
operator, athis
variable is set to the newly-created object. When invoking a method on an object,this
is set to that object itself. And when invoking a function in a browser environment,this
is set towindow
, otherwise known as the global object.
Along with all this, there is yet one more set of ways to invoke functions: withapply()
, and withcall()
. Both methods share quite a few similarities, and they each allow us to specify how we want to setthis
. We'll take a look at each of them in detail next!
Further Research
- The this operator on MDN