how to use this keyword in javascript

In JavaScript, the this keyword refers to the execution context in which code is currently running. It can have different values depending on how it is used.

Using this in a Function

When this is used inside a function, its value depends on how the function is called.

index.tsx
function greet() {
  console.log(`Hello, ${this.name}!`);
}

const person = {
  name: 'John',
  greet: greet
};

person.greet(); // logs "Hello, John!"
152 chars
11 lines

In this example, this inside the greet() function refers to the person object because the function is called on that object.

Using this in Object-Oriented Programming

In object-oriented programming, this is often used to refer to the current object instance.

index.tsx
class Car {
  constructor(make, model) {
    this.make = make;
    this.model = model;
  }

  drive() {
    console.log(`Driving a ${this.make} ${this.model}`);
  }
}

const myCar = new Car('Honda', 'Civic');
myCar.drive(); // logs "Driving a Honda Civic"
256 chars
14 lines

In this example, this inside the drive() method refers to the current Car instance that the method is being called on.

Using this in a Different Context

You can use the call() or apply() methods to set the value of this explicitly for a function invocation.

index.tsx
function greet() {
  console.log(`Hello, ${this.name}!`);
}

const person1 = { name: 'John' };
const person2 = { name: 'Jane' };

greet.call(person1); // logs "Hello, John!"
greet.call(person2); // logs "Hello, Jane!"
218 chars
10 lines

In this example, call() is used to specify that this should refer to person1 or person2.

gistlibby LogSnag