← All Posts

UWU Whats this? (In JavaScript)

anime-girl-holding-javascript-book

The this keyword is one of the most widely used and yet confusing concepts in JavaScript. If you’ve ever used class-based components and traditional functions in react, chances are you’ve stumbled upon this “ultra-sleek” line of code which you mindlessly bind to your constructor. this.handleClick = this.handleClick.bind(this);

if you’re still delaying understanding this, then this tutorial is for you; and those of you who don’t use react, sadly you guys arent off the hook. this keyword is used everywhere in javascript i.e so if you’re building web, desktop, or native android apps, you’ll encounter this :) Let’s get started

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