16.JavaScript语言的抽象(Abstract)类

虽然ECMAScript没有专门支持抽象类的语法,但是我们可以通过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 {}

new Bus();       //class Bus {}
new Vehicle();   //class Vehicle {}
//Error: Vehicle cannot be directly instantiated

原创文章,作者:huoxiaoqiang,如若转载,请注明出处:https://www.huoxiaoqiang.com/basic/js/4820.html

发表评论

登录后才能评论