← All Posts

UWU Whats this? (In JavaScript)

anime-girl-holding-javascript-book

What is this?

this is a keyword that references the object which is executing the current function. In simpler terms- It refers to an object.

And that object differs according to your functions, here are two examples -

If your function is in the Global Context i.e outside of any function -

In the global context, this refers to the global object.

  • In browsers, the global object is named the “window”.
  • In Node.js it’s called the “global” object.

Try to run this in your browser console ( or use RunJS )

console.log(this==window)
//it returns true

If you are using a method i.e a function which is a property of an object

In this state, this refers to the method’s object instead of the global object. here’s an example to help you understand better.

let teacher ={
	 professor : "Mr Feynman",
  age:58,
 greet(){
    console.log(`hello ${professor}`)
  }
}

teacher.greet()

Here we’ve created an object called teacher . In teacher, we have a method called greet, which console.logs a greeting using the professor variable in the object. If you try running the Greet method, we’ll encounter an error ReferenceError: professor is not defined.

This is because the context isn’t specified, try replacing console.log(hello ${professor}) to console.log(hello ${this.professor})

Here’s the result now, because this refers to the object of the method.

let teacher ={
	 professor : "Mr Feynman",
  age:58,
 greet(){
    console.log(`hello ${this.professor}`)
  }
}
teacher.greet()
//returns 'hello Mr Feynman'

But why do we use this keyword in the first place?

this allows us to reuse functions with different contexts. Mostly you’ll see this keyword used in constructor functions and the new keyword. Here’s an example of a constructor using this.

function User(name) {
  this.name = name;
  this.isAdmin = false;
}

let user = new User("Sahir");

console.log(user.name); // Sahir