9.1Classes & Constructors / Use Class

常に`class`を使用する

常に`class`を使用し、`prototype`を直接操作するのは避けます。`class`構文はより簡潔で理解しやすいです。

`class` 構文は、JavaScriptのプロトタイプベース継承を扱うためのシンタックスシュガー(糖衣構文)です。従来の `prototype` を直接操作する方法よりも、他のオブジェクト指向言語に慣れた開発者にとって直感的で読みやすく、コンストラクタやメソッドの定義が1か所にまとまります。

❌ Bad
// bad
function Queue(contents = []) {
  this.queue = [...contents];
}
Queue.prototype.pop = function () {
  const value = this.queue[0];
  this.queue.splice(0, 1);
  return value;
};
✅ Good
// good
class Queue {
  constructor(contents = []) {
    this.queue = [...contents];
  }
  pop() {
    const value = this.queue[0];
    this.queue.splice(0, 1);
    return value;
  }
}