javascript-today

This keyword

This keyword

Oh, this! It’s one of the trickiest concepts for beginners, but absolutely vital. The value of this inside a function depends on how the function is called, not where it’s defined (unless it’s an arrow function!).

Global Context: this refers to the global object (window in browsers, undefined in strict mode modules).

Method Call: this refers to the object the method is called on.

Constructor Call: this refers to the new instance being created.

Explicit Binding (call, apply, bind): You can explicitly set this.

Arrow Functions: Arrow functions do not have their own this. They inherit this from their enclosing lexical context. This is a huge reason why they’re so popular in callbacks.

const myObject = {
  name: 'Sarah',
  greet: function() {
    console.log(`Hello, my name is ${this.name}`);
  },
  arrowGreet: () => {
    console.log(`Hello, my name is ${this.name}`); // 'this' here refers to the global object (or undefined in strict mode modules)
  }
};

myObject.greet();       // Output: Hello, my name is Sarah (this is myObject)
myObject.arrowGreet();  // Output: Hello, my name is undefined (or empty, if run in browser global scope)

const standaloneGreet = myObject.greet;
standaloneGreet(); // Output: Hello, my name is undefined (this is window/global)