DevPath · Learn to code ESPTEN

Objects

Methods and this

Methods: functions inside objects

So far your objects only stored data. But they can act too: a property whose value is a function is called a method, and it's what lets the object "do things" instead of just holding them:

const calculator = {
  add: function (a, b) {
    return a + b;
  },
  // shorthand syntax (ES6):
  subtract(a, b) {
    return a - b;
  },
};
console.log(calculator.add(2, 3));      // 5
console.log(calculator.subtract(7, 4)); // 3

The this keyword

And how does a method reach its own object's data? With this. Inside a method, this points to the object through which the method is called. In the normal case, object.method(), that object is the one to the left of the dot, so this is like saying "myself": it gives you access to its other properties.

const person = {
  name: "Ana",
  greet() {
    return "Hi, I'm " + this.name;
  },
};
console.log(person.greet()); // "Hi, I'm Ana"

⚠️ Classic trap: this does not depend on where the method is defined, but on how it is called. If you "pull" the method out of its object and call it on its own, this is left orphaned and stops pointing to that object:

const f = person.greet;
f(); // this is no longer person → this.name would be undefined

We'll see how to fix this (with bind, or using classes) in the OOP module.

Important: arrow functions don't have their own this, which is why for object methods that use this the normal or shorthand syntax is usually preferred, not the arrow.

Examples

A bank account that modifies itself with this

const account = {
  balance: 100,
  deposit(amount) {
    this.balance = this.balance + amount;
    return this.balance;
  },
};
console.log(account.deposit(50)); // 150
console.log(account.balance);     // 150
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← Object literals and property accessIterating over objects: keys, values, and entries →