JavaScript this Keyword


What is this?

In JavaScript, this refers to the object that is executing the current function.

The value of this depends on how a function is called, not where it is written.

Global Context

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

  • In browsers, the global object is window.
console.log(this); // window

Inside an Object Method

When used in an object method, this refers to the object itself.

const person = {
  name: "Alice",
  greet() {
    console.log("Hello, I'm " + this.name);
  },
};
                                
person.greet(); // "Hello, I'm Alice"

this.name points to person.name.

❌ Detached Function (Loses Context)

const person = {
  name: "Alice",
  greet() {
    console.log(this.name);
  },
};
                                
const sayHello = person.greet;
sayHello(); // undefined (in non-strict mode) or error (in strict mode)

this is not bound, so it refers to the global object or undefined in strict mode.

🧲 Fixing this with bind, call, apply

const person = {
  name: "Bob",
};
                                
function greet() {
  console.log("Hello, " + this.name);
}
                                
greet.call(person);  // "Hello, Bob"
greet.apply(person); // "Hello, Bob"
                                
const greetPerson = greet.bind(person);
greetPerson();       // "Hello, Bob"
  • call() and apply() call the function immediately, passing a new this.
  • bind() returns a new function with the bound this.

Inside a Constructor Function

In a constructor function, this refers to the newly created object.

function Car(brand) {
  this.brand = brand;
}
                                
const myCar = new Car("Toyota");
console.log(myCar.brand); // "Toyota"

this in Arrow Functions

Arrow functions don’t have their own this. They inherit this from their parent scope.

const user = {
  name: "Alice",
  greet: () => {
    console.log(this.name); // undefined
  },
};
                                
user.greet();

Arrow functions are great when you want to preserve the surrounding this.

function Timer() {
  this.seconds = 0;
                                
  setInterval(() => {
    this.seconds++;
    console.log(this.seconds);
  }, 1000);
}
                                
new Timer(); // Correctly logs seconds

Summary Table

Context this Refers To
Global scope Global object (window)
Object method The object itself
Function (non-method) call Global object or undefined (strict)
Constructor function The new object created
Arrow function Inherits this from outer scope
With bind(), call(), apply() Manually defined object

🧪 Practice Exercise:

Task:

  1. Create an object with a method and use this to access properties.
  2. Try detaching a method and calling it separately — observe this.
  3. Use bind() to fix this in a detached function.
  4. Use arrow functions inside setTimeout to preserve outer this.
  5. Create a constructor that sets properties using this.