DevPath · Learn to code ESPTEN

Object-oriented programming

Objects and this

Objects with behavior

An object groups data (properties) and behavior (methods). A method is simply a function stored as a property:

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

The this keyword

Inside a method, this refers to the object the method was called on. That is why this.balance accesses the balance of that specific object.

this is dynamic: its value depends on how the function is called, not on where it was defined. When you call account.deposit(50), this is account.

Arrow functions do not have their own this: they inherit it from the surrounding context. That is why, for object methods, the method() { ... } syntax is usually preferred.

Examples

An object with a method and this

const counter = {
  value: 0,
  increment() {
    this.value++;
    return this.value;
  },
};
console.log(counter.increment());
console.log(counter.increment());
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 →
Classes, constructor and methods →