【问题标题】:JS Class AbstractionJS 类抽象
【发布时间】:2019-08-12 21:04:05
【问题描述】:

我一直在尝试创建一个可以修改继承类中的变量的抽象类,但是当我在继承类中设置一个空变量时,我遇到了一个问题,抽象类不会设置它?

此示例无效

class Abc {
  constructor() {
    this.id = "x";
  }
}
class Test extends Abc {
  id;
}

const test = new Test();
console.log(test)

这个例子可以工作

class Abc {
  constructor() {
    this.id = "x";
  }
}
class Test extends Abc {
}

const test = new Test();
console.log(test)

【问题讨论】:

  • 如果你想让一个子类实例有一个未定义的ID,把id;改成id = undefined;,是你想要的吗?
  • JS 不支持抽象类...
  • id; 作为 ES6 类的一部分无效。你在使用一些实验性语法吗?
  • “抽象类”是什么意思?可以轻松实例化new Abc
  • 当提出问题而不是说“这行得通”和“这行不通”时,您应该解释代码 做什么 ,您想要什么 它要做的事情和你尝试过的事情。

标签: javascript ecmascript-6 es6-class


【解决方案1】:

您可以使用 undefined 初始化它们的 id,但也可以在构造函数中将其设置为可选字段,以防在创建实例时设置。

在 JS 中不能有抽象类,但可以添加一个简单的验证来防止直接实例化:

class AbstractClass {
  constructor(id = undefined) {
    if (new.target.name === AbstractClass.name) {
      throw new Error("Can not create instance of Abstract class");
    }
    this.id = id;
  }
}

class DerivedClass extends AbstractClass {}

const disallowed = new AbstractClass(); // throws error 
const allowed = new DerivedClass(1); // will work fine

【讨论】:

  • 你甚至可以省略constructor(id) { super(id); },默认构造函数也是如此
猜你喜欢
  • 2012-09-23
  • 2011-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多