抽象类
虽然ECMAScript没有专门支持抽象类的语法,但是我们可以通过new.target来实现抽象类。通过在实例化时检测new.target是不是抽象基类,可以阻止对抽象基类的实例化。
class Vehicle {
constructor() {
console.log(new.target);
if (new.target === Vehicle) {
throw new Error('Vehicle cannot be directly instantiated');
}
}
}
//继承
class Bus extends Vehicle {}
//class Bus {}
new Bus();
//Error: Vehicle cannot be directly instantiated
new Vehicle();
重写
另外,可以在抽象基类构造函数中进行检查,可以要求派生类必须定义某个方法。
class Vehicle {
constructor() {
if (new.target === Vehicle) {
throw new Error('Vehicle cannot be directly instantiated');
}
if(!this.foo) {
throw new Error('Inheriting class must define foo()');
}
console.log('success!');
}
}
//派生类
class Bus extends Vehicle {
foo() {};
}
//派生类
class Van extends Vehicle {}
//success
new Bus();
//Error:Inheriting class must define foo()
new Van();
原创文章,作者:huoxiaoqiang,如若转载,请注明出处:https://www.huoxiaoqiang.com/javascript/javascriptlang/4820.html