var nextid = 0
function Animal(name) {
this.name = name
Object.defineProperty(this, 'nextid',
{value: nextid++, writable: false})
}
var animal1 = new Animal('dog')
var animal2 = new Animal('cat')
我想知道与使用闭包或工厂模式相比,这是否是一个好方法?
我的问题与此线程类似(建议关闭和工厂模式):
Incrementing object id automatically JS constructor (static method and variable)
最佳答案
Id 不应作为构造对象的一部分生成:它们应分配给对象。
想象一下体育比赛:运行者会选择他们的背部吗?
function Animal() {
}
var idGenerator = new IdGenerator();
var animal = new Animal();
animal.id = idGenerator.generate();
也许您仍然能够在构造函数中生成ids,但我会尝试避免硬编码id生成注入(inject)idGenerator
相反:
function Animal(idGenerator) {
this.id = idGenerator.generate();
}
顺便说一句,我的两分钱是你应该采用第一种方法:运行者不会自己分配背侧。
关于javascript - 递增对象 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42728762/