Hiprup

What is the 'this' keyword in JavaScript?

this refers to the object currently executing the function. Its value is decided by how the function is called, not where it is defined.

  • Method call — this is the object before the dot.

  • Plain function call — this is undefined in strict mode (or the global object otherwise).

  • Arrow function — no own this; it inherits from the surrounding scope.

  • call / apply / bind — set this manually.

  • new — this is the brand-new object being constructed.

Common trap: passing a method as a callback loses its this — bind it or wrap it in an arrow to keep the context.

// Implicit binding: this = the object before the dot
const user = {
  name: 'John',
  greet() { console.log(`Hi, ${this.name}`); }
};
user.greet(); // 'Hi, John' (this = user)

// Default binding: this = global/undefined
const greet = user.greet;
greet(); // 'Hi, undefined' (this = window or undefined in strict)

// Explicit binding: call, apply, bind
function introduce(greeting) {
  console.log(`${greeting}, I'm ${this.name}`);
}
introduce.call(user, 'Hello');     // 'Hello, I'm John'
introduce.apply(user, ['Hello']);   // 'Hello, I'm John'
const bound = introduce.bind(user);
bound('Hey');                      // 'Hey, I'm John'

// new binding: this = new object
function Person(name) {
  this.name = name; // this = the new instance
}
const p = new Person('Alice');
console.log(p.name); // 'Alice'

// Arrow function: this = enclosing scope
const team = {
  name: 'Dev Team',
  members: ['Alice', 'Bob'],
  print() {
    this.members.forEach(member => {
      console.log(`${member} is in ${this.name}`); // Arrow inherits this from print()
    });
  }
};
team.print(); // 'Alice is in Dev Team', 'Bob is in Dev Team'

Implicit: user.greet() — this is user. Default: standalone greet() — this is global (lost context). call/apply invoke with explicit this. bind returns a permanently bound function. new creates a fresh this.

Arrow function in forEach inherits this from print() — without arrow, this.name would be undefined inside forEach.

Know the 4 rules in priority order: new > explicit (call/apply/bind) > implicit (obj.method) > default (global/undefined). The 'lost context' gotcha (assigning method to variable) is the most asked.

Arrow functions inheriting this is the practical fix. Show call vs apply vs bind differences.

What is the 'this' keyword in JavaScript? | Hiprup