🎯

How to Use "this" Keyword in JavaScript

JavaScriptIntermediate

Understand context binding with this.

Code Example

JavaScript
// this in object method
const person = {
  name: "Alice",
  greet() {
    console.log(`Hello, I'm ${this.name}`);
  }
};
person.greet(); // "Hello, I'm Alice"

// this in regular function
function regularFunc() {
  console.log(this); // window (or undefined in strict mode)
}
regularFunc();

// Arrow functions don't bind this
const obj = {
  name: "Bob",
  regular: function() {
    console.log(this.name); // "Bob"
  },
  arrow: () => {
    console.log(this.name); // undefined
  }
};
obj.regular();
obj.arrow();

// bind, call, apply
function greet(greeting) {
  console.log(`${greeting}, ${this.name}`);
}

const user = { name: "Charlie" };
greet.call(user, "Hello"); // "Hello, Charlie"
greet.apply(user, ["Hi"]); // "Hi, Charlie"

const boundGreet = greet.bind(user);
boundGreet("Hey"); // "Hey, Charlie"

// this in class
class Counter {
  constructor() {
    this.count = 0;
  }
  
  increment() {
    this.count++;
  }
  
  getCount() {
    return this.count;
  }
}

const counter = new Counter();
counter.increment();
console.log(counter.getCount()); // 1

// this in event handlers
const button = document.querySelector("button");
button.addEventListener("click", function() {
  console.log(this); // the button element
});

// Arrow function in event handler
button.addEventListener("click", () => {
  console.log(this); // outer scope this
});

// Explicit binding with arrow function
class Timer {
  constructor() {
    this.seconds = 0;
    this.tick = () => {
      this.seconds++;
      console.log(this.seconds);
    };
  }
  
  start() {
    setInterval(this.tick, 1000);
  }
}

const timer = new Timer();
timer.start();

Explanation

this refers to the object calling the function. Arrow functions inherit this from parent scope. Use bind/call/apply to explicitly set this. Class methods bind this to instance.

Related Tutorials