node.JS计数对象实例



我有一个唯一id的对象,我想在构造函数中创建一个自动id生成器。我试过这个,它总是停留1
请帮助

getCounter  ()  {
Product.counter = (Product.counter || 0) + 1;
return Product.counter;
}
this.id = getCounter();

为什么不用class代替呢?

class Counter {
// Initialise the counter
constructor(counter = 0) {
this.counter = counter;
}
// When `inc` is called increment
// the counter value
set(n = 0) {
this.counter = this.counter + n;
return this;
}
// Return the current counter value
get() {
return `Count: ${this.counter}`;
}

}
// Create a new instance from the class
const counter = new Counter();
// Example: set the counter three times,
// and then return the current counter value
console.log(counter.set().set(5).set(10).get());

最新更新