限制类可以实例化的次数

gav*_*dix 1 javascript class instance

以下问题是在 JavaScript 面试中提出的。

创建一个类的 3 个实例后,如何防止进一步创建实例?

答案是什么?

Nik*_*des 5

我假设这个问题要求你变得“聪明”并且不使用任何全局变量或其他类。

您可以使用一种static方法来跟踪创建的实例。从那时起,您可以在 中抛出错误 constructor 以防止实例化。

class Foo {
  constructor(name) {
    if (Foo.maxInstancesReached())
      throw 'Max instances reached'

    this.name = name
  }

  static maxInstancesReached() {
    if (!this.numOfCreatedInstances)
      this.numOfCreatedInstances = 0

    return ++this.numOfCreatedInstances > 3
  }
}

const foo1 = new Foo('Jack')
const foo2 = new Foo('John')
const foo3 = new Foo('Mary')
const foo4 = new Foo('Rebecca')
Run Code Online (Sandbox Code Playgroud)