ES6 について調べているときに、抽象クラスについて何も見つけられなかったことに驚きました。(「抽象クラス」とは、Java の意味のことを言っています。抽象クラスは、インスタンス化できるようにサブクラスが実装する必要があるメソッド シグネチャを宣言します)。
ES6 で抽象クラスを実装するために採用されている規則を知っている人はいますか? 静的分析で抽象クラスの違反を検出できれば便利です。
抽象クラスのインスタンス化の試行を通知するために実行時にエラーを発生させる場合、エラーは何でしょうか?
ベストアンサー1
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