Reputation: 3
I am new to javascript, but I have some experience with Java. I am trying to create a program that lets a user create a task with a due date and description, which is then saved in a data structure until they complete it.
I want to add a unique identifier to each task when it is created and display it to the user, so they can use the identifier to look up the task later, (or at least I can use it to look up the task as the due dates and descriptions might not be unique).
My issue is, coming from Java, I want to create a "Task" class with the attributes I wish to save, as well as a unique identifier.
In Java, I would use a private static variable inside the class that would get increased each time a new instance of the class was created. However, this does not seem to work in javascript, and other stack overflow posts recommend workarounds that do not seem to apply to my situation.
I saw another post here that recommended using the "const" keyword, but that seems to throw an error when I try to update it.
What is the javascript version of a private static int variable that can live inside of a class which I can increase with each new instance?
Upvotes: 0
Views: 1946
Reputation: 9285
Javascript doesn't have static properties, only static methods. What I would do in your case is use a local variable declared outside the class. For example:
let counter = 0;
class Task {
constructor(name) {
this.id = counter++;
this.name = name;
}
}
console.log(new Task("Test A"));
console.log(new Task("Test B"));
Upvotes: 2