Functions as Methods

You can attach a function to an object. A function attached this way works much like a method in an object-oriented language.

Attaching Functions to Object Properties

Functions are first-class citizens, which means they can be treated like any other value. So a function can be assigned as a property of an object. You then call it through the object, the way you would call a method on a class in another language.

const account = {
  balance: 100,
  deposit: function (amount) {
    this.balance += amount;
  },
  withdraw: function (amount) {
    this.balance -= amount;
  },
};

account.deposit(50);
account.withdraw(20);
console.log(account.balance); // 130

In this example, deposit and withdraw are functions that change the balance property of the account object. The this keyword refers to the object the method was called on, so the function can read and write that object’s properties. (The rules for what this refers to are more involved than that. We will go through them in detail in the next section on Function Context.)

Simplified Method Syntax

Since ES6, you can define a method with a shorter syntax. It is closer to the way methods are written in traditional object-oriented programming.

const account = {
  balance: 100,

  deposit(amount) {
    this.balance += amount;
  },

  withdraw(amount) {
    this.balance -= amount;
  },
};

account.deposit(50);
account.withdraw(20);
console.log(account.balance); // 130

Both forms do the same thing. Use the traditional function syntax or this newer method syntax depending on whether you want clarity or brevity in your code.