<vetted />
JavaScript
Mid-Level
Question 5 of 10

How does 'this' work in JavaScript and what are some gotchas to watch for?

Quick Answer

The 'this' keyword refers to the execution context and its value depends on how a function is called, not where it's defined.

Detailed Answer7 paragraphs

The 'this' keyword in JavaScript refers to the object that is executing the current function. Unlike many other languages, its value is determined by how a function is called, not where it's defined.

In global context (or a regular function in non-strict mode), this refers to the global object (window in browsers, global in Node.js). In strict mode, this in a regular function is undefined.

When a method is called on an object (obj.method()), this refers to that object. This is implicit binding. However, if you extract the method and call it separately, you lose that binding: const method = obj.method; method() // this is not obj

Arrow functions don't have their own this binding. They inherit this from their enclosing lexical scope. This makes them ideal for callbacks where you want to preserve the outer this: class Timer { start() { setInterval(() => console.log(this), 1000) } }

You can explicitly set this using call(), apply(), or bind(). call and apply invoke the function immediately with a specified this; bind returns a new function with this permanently bound.

The new keyword sets this to the newly created object. Event handlers typically have this set to the element that triggered the event.

Understanding this is crucial for working with object-oriented JavaScript, event handlers, and debugging unexpected behavior in methods and callbacks.

Key Takeaway

The 'this' keyword refers to the execution context and its value depends on how a function is called, not where it's defined.

Ace your interview

Ready to Land Your Dream Job?

Join our network of elite AI-native engineers.