1. ホーム
  2. javascript

[解決済み] ECMAScript 6 には抽象クラスに関する規約がありますか?重複

2022-04-20 02:23:14

質問

ES6を読んでいて、抽象クラスについて何も書かれていないことに驚きました。(抽象クラスとは、Javaでいうところの、抽象クラスがメソッドシグネチャを宣言し、それをサブクラスが実装しなければインスタンス化できない、という意味です)。

ES6で抽象クラスを実装するために行われた規約をご存知の方はいらっしゃいますか?静的解析で抽象クラス違反を捕まえられるといいんだけど。

抽象クラスのインスタンス化の試みを知らせるために、実行時にエラーを発生させるとしたら、どのようなエラーになるでしょうか?

解決方法は?

ES2015 には、希望するデザイン・パターンを実現するためのアフォーダンスが組み込まれた Java スタイルのクラスはありません。しかし、何を達成しようとしているかに応じて、役に立つかもしれないいくつかのオプションがあります。

構築できないがサブクラスは構築できるクラスが欲しい場合は new.target :

class Abstract {
  constructor() {
    if (new.target === Abstract) {
      throw new TypeError("Cannot construct Abstract instances directly");
    }
  }
}

class Derived extends Abstract {
  constructor() {
    super();
    // more Derived-specific stuff here, maybe
  }
}

const a = new Abstract(); // new.target is Abstract, so it throws
const b = new Derived(); // new.target is Derived, so no error

の詳細については new.target ES2015 のクラスがどのように機能するかについての一般的な概要をお読みください。 http://www.2ality.com/2015/02/es6-classes-final.html

もし、特定のメソッドを実装することを特に求めているのであれば、スーパークラスのコンストラクタで確認することができます。

class Abstract {
  constructor() {
    if (this.method === undefined) {
      // or maybe test typeof this.method === "function"
      throw new TypeError("Must override method");
    }
  }
}

class Derived1 extends Abstract {}

class Derived2 extends Abstract {
  method() {}
}

const a = new Abstract(); // this.method is undefined; error
const b = new Derived1(); // this.method is undefined; error
const c = new Derived2(); // this.method is Derived2.prototype.method; no error