In this article, i don't want to take more times to explain how the this
keyword work. I will explain in clear terms and fastly. In fact, more developers are confused about the this
keyword.
What is ?
the this
keyword references the object that is executing the current function.
if a function is a method in a object,
this
reference that objectif a function is a regular or anonymous function,
this
reference the global object which is the window object in the browsers and global for nodejs
How it Work ?
if a function is a method in a object,
this
reference that object
let's to create our first example and to explain in more details. we are going to create a simple user object with object syntax literal
const user = {
name: "Emmanuel",
country: "Ivory Coast",
getAddress() {
console.log(this)
}
}
console.log(user.getAddress())
as we can see in the user object we have a method called getAddress()
and inside the method we have called the console.log(this)
to show in the console the result of our this
reference:
{
name: 'Emmanuel',
country: 'Ivory Coast',
getAddress: [Function: getAddress]
}
we can see that this
reference our user object. if we want to access for example the key name or country on each line inside the getAddress() method we can do that:
const user = {
name: "Emmanuel",
country: "Ivory Coast",
getAddress() {
console.log(this.name),
console.log(this.country)
}
}
In the console, the result is
Emmanuel
Ivory Coast
With ES6 classes is the same.
class Person {
constructor(name, country){ this.name = name, this.country = country}
getAddress() {console.log(this)}
}
let person = new Person('Emmanuel', 'Ivory Coast').getAddress()
console.log(person)
as we can see, we have to create a Person class and this class has the getAddress()
method to show the this
in the console, then we create a instance of our Person class and show the result:
we can see that the this
keyword reference our Person class
if a function is a regular or anonymous function,
this
reference the global object which is the window object in the browsers and global for nodejs
we are going to create a simple function called getVideos() and show the this
keyword in the console
function getVideos() {
console.log(this)
}
console.log(getVideos())
when we show the result in the console, we can see a global object window in the browser or global object in nodejs
Top comments (2)
A nice simplified explanation, yet not complete.
Shameless ad:
I've written an article describing a more complete way of finding out what
this
is.dev.to/ycmjason/let-me-explain-to-...
Thank you