
Hello folks!đ This article is all about the most interesting topic of JavaScript -this
.
this
points to a particular object. Now, what this object totally depends on how and where this
keyword is used.
Just remember the 6 golden rules and you are all set to gođđ-
- Global:- this âwindow
- Inside function:- this âwindow
- ES5 method:- this âobject
- ES5 function inside the ES5 method:- this âwindow
- ES6 function inside the ES5 method:- this âobject
- this inside ES6 arrow function always takes value from the parent scope(surrounding scope)
Globalđ

In the global scope, this points to the window object and thatâs why this.dog and window.dog have the same output.
Inside FunctionđŠ

Inside the function myDog() this refers to the window object and that is why this.dog returns âLabraâ and dog returns âShery â.
ES5 methodđ
this in ES5 method refers to the owner object.

Inside the ES5 method fullName, this refers to the owner object dog.
// this is refering to dog object
console.log(this.breed + â â + this.name) // Labra Shery console.log(dog.breed + â â + dog.name)// Labra Shery
ES5 function inside the ES5 methodđ±âđ
this in ES5 function inside the ES5 method points to the window object.

//Line 8
console.log(this.breed+â â +this.name) //Labra Shery
Line 8 prints âLabra Sheryâ because this inside the method points to the owner object i.e. dog.
//Line 10
console.log(this.breed+â â +this.name) //GoldenR Tucker
Line 10 printsâ GoldenR Tuckerâ because insideFunction() is inside the ES5 method fullName where this points to the window object. That is why this here refers to the global variable breed and name and this is where the problem arrives.
Now to resolve this issue, we can save the objectâs reference to some other variable say âselfâ and then we can use âselfâ in innerFunction to refer to the objectâs context.
Letâs see the same example

Because we have saved the dogâs reference at line no 9 inside âselfâ, therefore inside insideFunction()-
console.log(self.breed+â â +self.name); // Labra Shery
ES6 function inside the ES5 methodđ
Remember one rule â Arrow function always takes the value of this from the parent scope.
Inside the ES5 method, this refers to the owner object, in our case it is dog. Inside the ES5 method, if we add an arrow function, this inside it will take value from the parent i.e the ES5 method, therefore this inside the arrow function refers to the owner object i.e dog.

//Line 8
console.log(this.breed+â â +this.name) //Labra Shery//Line 10
console.log(this.breed+â â +this.name) //Labra Shery
In the next article, we will talk about this in call(), apply() and bind().
Thank you for reading this articleđ!