在 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/