Don P
Don P

Reputation: 63718

Create a class with a property that auto-increments on each class instantiation

How can I create a class where each instantiation of the class auto-increments an ID?

I have a solution that relies on an IIFE and a closure over an 'id' that auto-increments. Is there a better way though?

The only alternative I can think of is another class PersonFactory that tracks the UID and has a method for creating Person with its own auto-increment UID.

class Person {
    constructor(id, name){
        this.id = id;
        this.name = name;  
    }
}

// A factory that auto-increments the id given to each person
const PersonFactory = (function(){
    let id = 0;

    return (name) => {
        id++;
        return new Person(id, name);
    }
})();

const jenny = PersonFactory('Jenny'); // ID: 1
const eliza = PersonFactory('Eliza'); // ID: 2

Upvotes: 1

Views: 391

Answers (1)

Don P
Don P

Reputation: 63718

(Posted too soon)

The answer is static variables in your class!

Now you don't need a loosely related object to track state outside of an instantiation.

class Person {
    static #id = 0;

    static #incrementID() {
        this.#id++; 
    }

    constructor(name){
        Person.#incrementID();
        this.id = Person.#id;

        this.name = name;  
    }
}

const jenny = new Person('Jenny'); // ID: 1
const eliza = new Person('Eliza'); // ID: 2

console.log(jenny.id)
console.log(eliza.id)

Upvotes: 2

Related Questions