SyntaxStudy
Sign Up
JavaScript Object Methods and the this Keyword
JavaScript Intermediate 8 min read

Object Methods and the this Keyword

Object Methods and the this Keyword

When a function is stored as a property of an object, it is called a method. Inside a method, the keyword this refers to the object the method was called on — the receiver. Understanding how this is determined is one of the most important concepts in JavaScript.

Regular Methods

In a regular function method, this is set by how the function is called, not where it is defined. Calling obj.method() sets this to obj.

Arrow Functions and this

Arrow functions do not have their own this — they inherit this from the surrounding lexical scope. This makes them unsuitable as object methods (where you need this to refer to the object) but ideal for callbacks inside methods.

Losing this

Storing a method reference in a variable or passing it as a callback detaches it from its object. Use .bind(obj) to permanently bind this, or arrow functions to capture it lexically.

Example
const counter = {
  count: 0,
  increment() {
    this.count++;
  },
  reset() {
    this.count = 0;
  },
  getCount() {
    return this.count;
  }
};
counter.increment();
counter.increment();
counter.increment();
console.log(counter.getCount()); // 3
counter.reset();
console.log(counter.getCount()); // 0
const obj = {
  name: 'Test',
  arrowMethod: () => 'this.name is: ' + typeof this,
  regularMethod() { return this.name; }
};
console.log(obj.regularMethod()); // 'Test'
console.log(obj.arrowMethod());   // 'this.name is: undefined'
Pro Tip

Never use arrow functions as object method definitions when the method needs to reference the object via this — use the concise method shorthand or a regular function expression instead.