Mastering the ‘this’ Keyword in JavaScript: Tips and Tricks for Beginners
As a beginner in JavaScript, you may have come across this
keyword and not fully understood its purpose. This can be a confusing concept, especially since the value of this
can change depending on the context in which it is used. In this guide, I’m going over what this
is and how it works in JavaScript.
Before jumping to explain what this
is I want to walk you through some other concepts in JavaScript. That being said, this post is like Netflix show “Kaleidoscope” the order of sections doesn’t matter so feel free to jump around.
Binding
The bind
method in JavaScript creates a new function with the same body and parameters as the original function, but with a permanently bound value for the this
keyword. It allow you to specify what the value of this
should be when the function is called.
There are several ways to bind a function in JavaScript, but the most common method is using the bind method.
The bind method is a function that is available on all functions in JavaScript, and it returns a new function with this
value set to the provided argument. Here’s an example of how to use the bind method:
function sayHello() {
console.log(`Hello, my name is ${this.name}`)
}
const person = { name: 'John' }
const sayHelloAsJohn = sayHello.bind(person)
sayHelloAsJohn() // Hello, my name is John
sayHello(person) // Hello, my name is
In this example, we have a function called sayHello
that logs a greeting using the value of the name property of the object that it is called on. We then create a new function called sayHelloAsJohn
by calling the bind method on sayHello
and passing in the person object as an argument.
When we call sayHelloAsJohn
, it logs the greeting with the name property of the person
object, even though it was not called as a method on the person object.
This is because in this case in sayHello
function this
refers to the person
object. But when you call sayHello
without binding, this
refers to the global object and name doesn’t exists in this global object.
Call-Site
In JavaScript, the call-site refers to the location in the code where a function is called (i.e., invoked). The value of the this
keyword inside a function is determined by the call-site of the function.
Back to “this
” keyword
this
is a keyword that refers to the object that the current function is being called on. In other words, this
is a way to refer to the object that owns the currently running code (wait a minute, what does that even mean? the examples will help you to understand this concept better).
So, how do we determine the value of this
? The value of this
is determined by how a function is called, not where it is defined. This, as we talked about it, is known as the call-site of the function.
There are four main ways to invoke a function in JavaScript, and each one sets the value of this
differently:
As a function
When a function is called as a function, this is set to the global object (window in the browser, global in Node.js).
In this example, the sayHello
function is called as a function, so the call-site is the global context.
function sayHello() {
console.log(this);
// prints the global object
/*
Window {window: Window, self: Window, document: document, name: "",
location: Location, …}
*/
}
sayHello();
As a method
When a function is called as a method (i.e., a function that is a property of an object), this is set to the object that the method is called on.
In this example, the sayHello
function is called as a method on the person
object, so the call-site is the person
object. This means that the value of this
inside the function is set to the person
object.
const person = {
name: 'John',
sayHello: function() {
console.log(this); // prints the person object
// {name: "John", sayHello: ƒ}
}
}
person.sayHello();
Using the call or apply methods:
The call and apply methods allow you to set the value of this
manually by passing in an object as an argument.
In this example, we use the call
method to invoke the sayHello
function and set the value of this
to the person
object. This allows us to use the sayHello
function in a different context than it was originally defined in, and the value of this
inside the function will be the person
object.
function sayHello() {
console.log(this);
}
const person = { name: 'John' };
sayHello.call(person); // prints the person object
// {"name": "John"}
Using the bind method
The bind method creates a new function with a fixed value for this
.
In this example, the value of this
inside the function is set to the person
object because that is the argument that was passed to the bind
method when the new function was created.
The call-site for the sayHello
function is different when it is called as sayHelloAsJohn()
compared to when it is called as sayHello()
. When it is called as sayHello()
, the call-site is the global context, and the value of this
is set to the global object (window
in the browser, global
in Node.js).
function sayHello() {
console.log(this);
}
const person = { name: 'John' };
const sayHelloAsJohn = sayHello.bind(person);
sayHelloAsJohn(); // prints the person object
// {"name": "John"}
It’s important to note that the value of this
can be changed using any of the above methods, even if the function was originally defined as a method or with a fixed value for this
.
const person = {
name: 'John',
sayHello: function() {
console.log(this.name);
}
}
const sayHelloAsSomeoneElse = person.sayHello.bind({ name: 'Jane' })
sayHelloAsSomeoneElse() // prints 'Jane'
person.sayHello() // prints 'John'
Summary
The this
keyword in JavaScript refers to the object that is currently executing the code, and its value is determined by the call-site of the function. The four main ways to invoke a function in JavaScript are as a function, as a method, using the call or apply methods, and using the bind method. Each of these sets the value of this differently.
It’s important to understand how this
works in JavaScript because it can be a source of confusion and bugs if not used correctly.