Methods & this

Object Methods

Example

A method is a function stored as a property. Inside it, this refers to the object the method was called on:

const person = {
  firstName: "Asha",
  lastName: "Rao",
  fullName() {
    return this.firstName + " " + this.lastName;
  },
};
console.log(person.fullName());

Output

Asha Rao

Losing this

Example

this depends on how a function is called, not where it is defined. Detached from the object, the method loses it. Arrow functions do not have their own this at all:

const timer = {
  label: "Timer",
  regular() { return this?.label; },
  arrow: () => typeof this,
};
const detached = timer.regular;
console.log(timer.regular());
console.log(detached());          // called without an object
console.log(timer.arrow());

Output

Timer
undefined
object

More on this, call, apply and bind in Advanced Functions.