Search code examples
javascriptoopobjectclosuresprototype-programming

Incrementing object id


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')

I wonder if this is a good way compared to using a closure or a factory pattern?

My question is similar to this thread(closure and factory pattern suggested):

Incrementing object id automatically JS constructor (static method and variable)


Solution

  • Those closures and factory patterns in the linked answer exist solely to encapsulate the nextid variable in a local scope or factory instance. How you create the animal - as a plain object, as a class instance, or an instance with a readonly property - has nothing to do with this. Each of them are equally good.

    Whether you actually need the encapsulation depends on your modularisation approach (e.g. the closure is pointless in a node module) and the uniqueness requirements for ids.