JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsjavascript
PrevNext
javascript
mid
this

How does the 'this' keyword work in JavaScript?

this
scope
binding
call
apply
bind
arrow-functions
Quick Answer

The value of 'this' depends on how a function is called: in a method, it refers to the object; in a regular function, it's the global object (or undefined in strict mode); in arrow functions, it's lexically inherited from the enclosing scope.

Detailed Explanation

'this' binding rules (in order of precedence):

  1. new binding: When called with 'new', 'this' is the newly created object

  2. Explicit binding: Using call(), apply(), or bind() explicitly sets 'this'

  3. Implicit binding: When called as object method, 'this' is the object

  4. Default binding: In non-strict mode, 'this' is global object; in strict mode, undefined

Arrow functions:

  • Don't have their own 'this'
  • Inherit 'this' from enclosing lexical scope
  • Cannot be changed with call/apply/bind

Common pitfalls:

  • Losing 'this' in callbacks
  • Event handlers in classes
  • Nested functions

Code Examples

Different 'this' contexts
// 1. Method call - 'this' is the object
const obj = {
  name: 'Alice',
  greet() {
    console.log(this.name);
  }
};
obj.greet(); // 'Alice'

// 2. Function call - 'this' is global/undefined
const greet = obj.greet;
greet(); // undefined (strict) or window.name

// 3. Constructor call - 'this' is new instance
function Person(name) {
  this.name = name;
}
const bob = new Person('Bob');
console.log(bob.name); // 'Bob'

// 4. Arrow function - 'this' from lexical scope
const obj2 = {
  name: 'Charlie',
  greet: () => {
    console.log(this.name); // 'this' from outer scope
  }
};
obj2.greet(); // undefined (not obj2)

Resources

MDN - this

docs

JavaScript.info - Object methods, this

article

You Don't Know JS - this & Object Prototypes

book

Related Questions

What is a closure in JavaScript and why are they useful?

mid
closures

Explain JavaScript's prototype chain and how inheritance works.

senior
prototypes
Previous
Explain the JavaScript Event Loop and how it handles asynchronous operations.
Next
What is the difference between shallow copy and deep copy in JavaScript, and how do you create each?