iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS this Keyword

this is JavaScript's most misunderstood keyword. Its value depends on how a function is called — not where it's defined.

The rules in order

Call stylethis is…
Method: obj.fn()obj
Constructor: new Fn()A fresh object
Explicit: fn.call(x) / fn.apply(x) / fn.bind(x)x
Plain: fn()undefined in strict mode; window otherwise
Arrow functionInherits from the enclosing scope — does not rebind

The classic trap

JS
const user = {
  name: "Ada",
  greet: function () { console.log(this.name); }
};

user.greet();                   // "Ada"  ✓ method call

const grab = user.greet;
grab();                         // undefined ✗ — plain call

Three fixes

JS
// 1. Bind a permanent this
const greet = user.greet.bind(user);
greet();                        // "Ada"

// 2. Arrow function captures the surrounding this
class Timer {
  constructor() {
    this.tick = () => console.log(this);   // inherits Timer instance
  }
}

// 3. Wrapper function
setTimeout(() => user.greet(), 0);
Note: Inside an event handler, this is the element that fired the event — when written with a regular function. Arrow handlers do not get that auto-binding.
Tip: Default to arrow functions for inner callbacks. Their "no own this" rule means you don't have to remember any of the rules above — they always use the surrounding this.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from JS this Keyword!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Permanently lock `this` for greet() to the user object.

const fn = user.greet. (user);

Test yourself

Q1. Arrow functions and `this`…
Q2. In strict mode, a plain `fn()` call sets `this` to…
Q3. Permanently bind `this` for a function with…

Discussion

Loading…