当我在研究ES6时,惊讶地发现没有关于抽象类的内容。(我所说的“抽象类”是指Java中的概念,即抽象类声明方法签名,子类必须实现这些方法才能被实例化)
有人知道在ES6中已经出现了哪些惯例来实现抽象类吗?能够通过静态分析捕获抽象类违规将是很好的。
如果我在运行时引发一个错误来表示对抽象类进行实例化的尝试,那么错误会是什么?
当我在研究ES6时,惊讶地发现没有关于抽象类的内容。(我所说的“抽象类”是指Java中的概念,即抽象类声明方法签名,子类必须实现这些方法才能被实例化)
有人知道在ES6中已经出现了哪些惯例来实现抽象类吗?能够通过静态分析捕获抽象类违规将是很好的。
如果我在运行时引发一个错误来表示对抽象类进行实例化的尝试,那么错误会是什么?
ES2015没有像Java那样内置支持您期望的设计模式的类。但是,它有一些选项可能会有所帮助,具体取决于您要完成的任务。
如果您想要一个无法构造但其子类可以构造的类,则可以使用new.target
:
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
new.target
,转换后的代码会抛出错误:SyntaxError: Unexpected token '.'
。 - siannone
mymethod(){throw new NotImplementedError()}
。 - Matthew Pautzke