Creating a serial number in a Class without relying on a global variable is a useful technique that

I am looking for a way to assign a unique ID to each instance of a Class without relying on global variables. I have tried using a global variable and incrementing it, but I would prefer a more efficient approach.

Is there a way to generate an ID within the Class itself, avoiding the use of 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

Answer №1

A suggested approach is to place the counter directly within the Member object.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best method for displaying an HTML string within an HTML file in Angular 5?

I have declared an array in my TypeScript file like this: import {Component, OnInit} from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser'; @Component({ selector: 'app-foo', template: ...

Extracting text from an HTML file and passing it to an Express.js server: A beginner

Currently, I'm attempting to retrieve the values from an HTML text field and store them in variables. I require HTML to capture these values and return the response within the .html file. HTML: <body> <form> ...

Transform special characters into HTML entities

$scope.html = '&lt;script&gt;'; Is there a way for Javascript to convert &lt;script&gt; back to <script>, similar to how PHP does it? ...

What should be transmitted to the front-end following the successful validation of a token on the server?

My process starts with a login page and then moves to the profile page. When it comes to handling the token on the backend, I use the following code: app.use(verifyToken); function verifyToken(req, res, next) { if (req.path === '/auth/google&ap ...

Node app experiencing issues with passport authentication request route only in production mode

Currently, I am facing an issue with my MERN app that includes passport for authentication flow. It runs smoothly in development mode but encounters major problems in production mode that I am struggling to resolve. The bug seems elusive and I can't p ...

What is the method for creating a class in PHP without the ability to instantiate objects from it?

Is it possible to define a class in PHP without allowing the creation of its object? Are there any alternative methods for achieving this? ...

Effortlessly transfer files with Ajax through Box

I attempted to utilize the Box.com API for file uploads according to instructions from https://gist.github.com/seanrose/5570650. However, I encountered the following error message: `XMLHttpRequest cannot load "". No 'Access-Control-Allow-Origin&ap ...

I'm wondering if there exists a method to arrange a multi-array in javascript, say with column 1 arranged in ascending order and column 2 arranged in descending order?

Here is an example of a randomly sorted multi-array: let arr = [[3, "C"], [2, "B"], [3, "Q"], [1, "A"], [2, "P"], [1, "O"]]; The goal is to sort it in the following order: arr = [[1, "O" ...

Browsing HTML Documents with the Click of a Button

After collecting JSON data from a SharePoint list, I am currently in the process of creating an HTML Document. At this point, I have completed approximately 80% of the expected outcome. Due to Cross-Origin Resource Sharing (CORS) restrictions, I have hard ...

Wait for Axios Request Interceptor to complete before sending another ajax call

One feature I have added is a request interceptor for all axios calls. This interceptor checks the JWT token and automatically refreshes it if necessary. axios.interceptors.request.use((config) =>{ const currentState = store.getState(); // get upd ...

When a React component written in TypeScript attempts to access its state, the object becomes

Throughout my app, I've been consistently using a basic color class: const Color = { [...] cardBackground: '#f8f8f8', sidebarBackground: '#eeeeee', viewportBackground: '#D8D8D8', [...] } export defau ...

Trouble with AJAX BitMovin: unable to process GET request

I've been struggling to find a solution to my problem as I cannot pinpoint what exactly to search for. My current issue involves using AJAX for a PHP Get request, causing it to submit and navigate away from the page. The BitMovin library appears to b ...

Assistance needed with sending JSON data to a PHP server using the POST method

I am attempting to transfer JSON data from an HTML form to a PHP server using the POST method. The issue I am encountering is that my code always ends up in the fail block within the callback function. Despite this, the Firebug console (ctrl+shift+J) does ...

The conversion of string to number is not getting displayed correctly when using console.log or document.write. Additionally, the concatenated display is also not functioning as intended

Being new to JS and HTML, this program was created to enhance my understanding of the concepts. I attempted a basic program to convert a string to a number in three different ways, but I am having trouble determining if the conversion actually took place. ...

Creating multiple AJAX contact forms can be achieved by modifying the code to accommodate multiple forms on a single page. Here's

My one-page website features 15 identical contact forms all with the same ID, created using basic PHP. Unfortunately, I am facing an issue where AJAX is only working for the first form. When submitting any other form, it simply opens a white page with a "T ...

Performing a jQuery ajax POST request to log users in

I am currently facing a challenge with my .ajax request being made through a form for the purpose of logging in. Upon submitting my form, I am not receiving any response from either the success or error functions. Interestingly, even when I inserted an a ...

v-treeview component triggering method execution twice upon input

I'm facing an issue with my Vue component that contains a treeview. Upon selecting a node, the goal is to update an array and display the checkbox as selected. However, I'm encountering a problem where if I select elements from one folder in the ...

Combining two lists in immutable.js by flattening and zipping

When faced with two immutable lists, such as: const x = [5,6,7]; const y = [x,y,z,w]; Is there a straightforward method to combine/interleave them in order to obtain: const z = [5,x,6,y,7,z,w]; ...

Angular service providing a subset of resource data

I am currently working with an Angular factory called DogePrice: .factory('DogePrice', ['$resource', function ($resource) { return $resource("https://chain.so/api/v2/get_info/DOGE"); }]) Usually, the API response looks like this: ...

Submitting a form with AJAX and additional fields can be accomplished by including the extra fields in

Imagine a scenario where I am working with a basic form like the one below <%= form_for(@category) do |f| %> <% if @category.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@category.errors.count, "erro ...