javascript - 限制一个类可以被实例化的次数

标签 javascript class instance

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

After creating 3 instances of a class, how to prevent further instance creation?

这个问题的答案是什么?

最佳答案

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

您可以使用 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')

关于javascript - 限制一个类可以被实例化的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48069368/

相关文章:

javascript - 将当前时间添加到我页面上的特定部分

php - https 安全 cookie 是否可以防止 XSS 攻击?

.net - 您是否必须在 VB.NET 中显式创建表单实例?

javascript - 将变量设置为函数的实例

javascript - Angular 1.5+ 中组件的 DOM 操作

javascript - 在 Plain JS Script 之前和之后加载 ES6 模块依赖项

c++ - 映射、类、成员函数

Python 装饰类不允许方法调用。为什么?

c++ - 复制在我的 string::copy 实现中不起作用

Android Intent with Cordova - 每次分享都会启动新的应用程序实例。应该只有一个