Home > OS >  How to generate serial number in Class without using global variable
How to generate serial number in Class without using global variable

Time:11-13

I would like to generate an ID for each instance of a Class. I tried counting up using a global variable. It works, but I don't want to use the global space.

How can I generate an ID only in the Class without using global variables?

let id = 0;

class Member {
  constructor(firstName, lastName, birthDay) {
    this.id =   id;
    this.firstName = firstName;
    this.lastName = lastName;
    this.birthDay = birthDay;
  }
}

const m1 = new Member('Oliver', 'Cruz', '11/13/1990');
console.log(m1.id); // 1

const m2 = new Member('Sophia', 'Brown', '11/30/1992');
console.log(m2.id); // 2

CodePudding user response:

You can put the counter directly on Member.

class Member {
  static membersCreated = 0;
  constructor(firstName, lastName, birthDay) {
    Member.membersCreated  ;
    this.id = Member.membersCreated;
    this.firstName = firstName;
    this.lastName = lastName;
    this.birthDay = birthDay;
  }
}

const m1 = new Member('Oliver', 'Cruz', '11/13/1990');
console.log(m1.id); // 1

const m2 = new Member('Sophia', 'Brown', '11/30/1992');
console.log(m2.id); // 2

  • Related