Как переопределить статическое свойство при наследовании класса?

Есть класс Product, имеющий статическое свойство id. Это необходимо, чтобы каждый экземпляр получал свой id (в порядке создания экземпляра). Также есть класс Raiting, который наследуется от Product. Как можно сделать так, чтобы у класса Raiting было свое статическое свойство ID, не зависящее от родительского класса?

class Product {
  static id = 0;
  constructor(title, price, oldPrice, url) {
    Product.id++
    this.id = Product.id;
    this.title = title;
    this.price = price;
    this.oldPrice = oldPrice;
    this.sale = oldPrice - price;
    this.url = url;
    this.alt = title
  }
  currency = 'руб';

}

class Raiting extends Product {
    constructor(title, price, url, raiting) {
    super(title, price, url);
    this.raiting = raiting;
  }
  starHref = 'img/icons/icons.svg#star';
}

Ответы (1 шт):

Автор решения: Grundy

статические поля не наследуются. Если нужно что-то переопределить, стоит использоваться обычные методы, которые, в зависимости от реализации, могут внутри себя использовать статические методы:

class Product {
  static id = 0;
  getId() {
    return ++Product.id;
  }
  constructor(title, price, oldPrice, url) {

    this.id = this.getId();
    this.title = title;
    this.price = price;
    this.oldPrice = oldPrice;
    this.sale = oldPrice - price;
    this.url = url;
    this.alt = title
  }
  currency = 'руб';

}

class Raiting extends Product {
  static id = 0;
  getId() {
    return ++Raiting.id;
  }
  constructor(title, price, url, raiting) {
    super(title, price, url);
    this.raiting = raiting;
  }
  starHref = 'img/icons/icons.svg#star';
}

console.log('Product', new Product().id);
console.log('Product', new Product().id);
console.log('Raiting', new Raiting().id);
console.log('Product', new Product().id);
console.log('Raiting', new Raiting().id);

→ Ссылка