Functions, objects, and the this
keyword are all interconnected in JavaScript. When a function is called, a this
variable is set to a specific object. However, the value of this
depends on just how the function was called.
In this post, we’ll explore different ways we can call functions, as well as how each of these sets the value of this
a bit differently.
“This” in constructor functions.
One place where you’ll commonly see the this
keyword is within constructor functions. Consider the following example:
function Course(id, name) {
this.id = id;
this.name = name;
this.describe = function () {
console.log(`Course ${this.id}: ${this.name}`);
};
}
const spanish = new Course("SPA-001", "Spanish 1");
In the above Course()
constructor, the describe
method references this.id
and this.name
. Since we invoke the Course()
function with the new operator, this
gets set to the newly-created object: spanish
.
{
id: "SPA-001",
name: "Spanish 1",
describe: function () {
console.log(`Course ${this.id}: ${this.name}`);
}
}
As a result, since this
becomes the spanish
object, and we can access properties directly from that object:
console.log(spanish.id); // "SPA-001"
console.log(spanish.name); // "Spanish 1"
What’s more: the describe()
method can effectively use this
to access the id
and name
properties of that object. This makes the following method call possible:
console.log(spanish.describe()); // "Course SPA-001: Spanish 1"
To recap: when we invoke a constructor function with the new operator, the value of this
gets set to that newly-created (i.e., instantiated) object.
“This” in methods.
Another place where you’ll commonly see this
is within object methods. In this context, the value of this
is actually not assigned to anything until an object calls the method where this
is used. In other words, the value assigned to this
is based on the object that invokes the method where this
is defined.
Consider the following example:
const printer = {
print: function () {
console.log("Printing...");
},
printTwice: function () {
this.print();
this.print();
},
};
If we invoke the printer
object’s methods:
printer.print();
// "Printing..."
printer.printTwice();
// "Printing..."
// "Printing..."
We know that when we call printer.print()
(or printer.printTwice()
) a variable this
gets set. Since this
can access the object it was called on (that is, printer
), printTwice
can use this
to directly access the printer
object, which contains the print
method. In other words: this.print()
tells printTwice
to look at printer
– the object that the method was called on – to find print
.
As such, when invoking a method on an object, this
gets set to the object itself!
“This” in functions.
So far, we’ve seen what happens to this
when invoking a constructor function with the new operator, as well as what happens to this
when calling a function that belongs to an object (i.e., a method). What happens when we simply invoke a regular function on its own?
Consider the following function that simply returns this
:
function funFunction() {
return this;
}
When we invoke funFunction()
, this
set to the window object, which is the global object if the host environment is the browser.
funFunction(); // (returns the global object, window)
To check the properties and methods available in the returned object, try running the above code in your browser’s developer console (e.g., Chrome DevTools).
“This” keyword, recapped.
When a function is called, a variable this
gets set to a certain value. But depending on how the function was called, what this
refers to can be very different:
- If a constructor function is called with a new operator,
this
is set to the newly-created object - If a method is called on an object,
this
is set to that particular object itself - If a normal function is simply invoked,
this
is set to the window (or global) object
Learn more.
Along with all this, there are yet more ways to invoke functions: with apply(), and with call(). Both methods share quite a few similarities, and they each allow us to specify how we want to set this
.
For a closer look at those methods, as well as an extended overview of the this
keyword in JavaScript, check out these resources:
- Lesson 3 of Object-Oriented JavaScript
- this on MDN
- The call() method on MDN
- The apply() method on MDN