what is this in javascript

In JavaScript, this refers to the object that owns the current executing code. It usually refers to the object that called the function where this keyword is used. The value of this keyword can be different depending on how a function is called.

Here are different scenarios and their corresponding values of this:

index.tsx
// 1. In a function call
function sayHello() {
  console.log(this);
}
sayHello(); // window object

// 2. In a method call
const person = {
  name: 'John',
  sayName: function() {
    console.log(this);
  }
}
person.sayName(); // person object

// 3. In an object's method that uses a callback function
const car = {
  brand: 'Toyota',
  startEngine: function() {
    console.log(`Starting ${this.brand}'s engine`);
  },
  logName: function(callback) {
    callback();
  }
}
car.logName(car.startEngine); // window object (because startEngine is detached from car object)

// 4. Using call(), apply(), or bind()
const truck = {
  brand: 'Ford'
}
car.startEngine.call(truck); // Ford's engine
692 chars
33 lines

related categories

gistlibby LogSnag