this in JavaScriptđŸ‘»

Prachi
3 min readOct 1, 2020

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😃💗-

  1. Global:- this →window
  2. Inside function:- this →window
  3. ES5 method:- this →object
  4. ES5 function inside the ES5 method:- this →window
  5. ES6 function inside the ES5 method:- this →object
  6. 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🙏!

--

--