← Вернуться к курсу: JavaScript from scratch

Classes, inheritance and this

Видео скоро появится

When you need to create many objects with the same structure and behavior, like a hundred users or fifty products, repeating the braces every time is awkward. A class is a template for making objects. Each object created from the class is called an instance. The class syntax arrived with ES6 and today it is the standard way to organize object-oriented code in JavaScript.

Constructor and methods

The special constructor method runs when you create an instance with new and is used to initialize its properties. Inside the class, this refers to the current instance. The other methods are written without the word function and are shared among all instances. If you forget new, JavaScript throws an error. By convention class names start with a capital letter. You can also define getters and setters, which are used like properties but run code.

javascript
class Product {
  constructor(name, price) {
    this.name = name;
    this.price = price;
  }

  withTax(rate = 0.21) {
    return this.price * (1 + rate);
  }

  get label() {
    return `${this.name} (${this.price} EUR)`;
  }
}

const lamp = new Product('Lamp', 100);
console.log(lamp.label);    // Lamp (100 EUR)
console.log(lamp.withTax()); // 121 (approximately)
console.log(lamp instanceof Product); // true

Inheritance with extends and super

A class can inherit from another with extends, reusing its properties and methods and adding or changing its own. In the constructor of the child class you must call super(...) before using this; that runs the parent class constructor. You can also call a parent method with super.method(). Use inheritance when there is a clear type relationship (a cat is an animal); if in doubt, it is usually better to combine smaller objects.

javascript
class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    return `${this.name} makes a sound`;
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name); // must come first
    this.breed = breed;
  }
  speak() {
    return `${super.speak()} - Woof!`;
  }
}

const rex = new Dog('Rex', 'Labrador');
console.log(rex.speak()); // Rex makes a sound - Woof!
console.log(rex instanceof Animal); // true

The problem with this

The value of this depends on how the function is called, not on where it is written. If you take a method out of its object and run it alone, this is lost and you get an error or undefined. This happens, for example, when passing a method as a callback. Solutions: use an arrow that calls it, use bind or define the method as a property with an arrow. Private properties are marked with # and are accessible only inside the class, ideal for protecting internal state.

javascript
class Counter {
  #count = 0; // private field

  increment() {
    this.#count++;
    return this.#count;
  }
}

const counter = new Counter();
console.log(counter.increment()); // 1
// console.log(counter.#count);   // SyntaxError: private

const user = {
  name: 'Eli',
  hello() { return `Hi ${this.name}`; }
};
const lost = user.hello;
// lost() would fail: this is no longer user
const bound = user.hello.bind(user);
console.log(bound());           // Hi Eli
console.log((() => user.hello())()); // Hi Eli

Static methods and when to use classes

A static method belongs to the class and not to the instances; it is called directly on the class name and is useful for related helper functions, such as creating an object from a different format. That said, not everything needs a class. If you only group data, a simple object is enough; if you only have one function, write a function. Classes shine when several objects share behavior and keep their own state, like a bank account, a cart or a game character. Choose the simplest tool that solves the problem.

javascript
class Temperature {
  constructor(celsius) {
    this.celsius = celsius;
  }
  static fromFahrenheit(f) {
    return new Temperature((f - 32) * 5 / 9);
  }
  toString() {
    return `${this.celsius.toFixed(1)} C`;
  }
}

console.log(String(Temperature.fromFahrenheit(212))); // 100.0 C

✎ Мои заметки

Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов

← НазадДалее →