Reputation: 1234
I am trying to create a Class in Javascript (Or whatever the equivalent is) that stores a count in a Class Variable so the constructor can assign an id to the created objects. Something like the following:
Shift = function(hour) {
this.id = Shift.idCount;
Shift.idCount++;
}
However I have no idea where idCount should be initialized or even defined. Is there a way of doing this?
Upvotes: 0
Views: 939
Reputation:
Yes, just say
Shift.idCount = 0;
after the definition of the Shift
function.
That allows you to access the current value of the counter whenever you want (if you want). If you don't want to directly access the value of the counter, and don't want anyone else to either, then use a private variable inside Shift
as @Pointy proposes.
Upvotes: 1
Reputation: 413682
I'd do it with a closure:
var Shift = function() {
var idCount = 1; // initial id
return function Shift(hour) { // this is the actual constructor
this.id = idCount++;
// other initialization ...
};
}();
var aShift = new Shift(9);
alert(aShift.id); // 1
var anotherShift = new Shift(17);
alert(anotherShift.id); // 2
That uses an anonymous wrapper function to provide a closure in which the counter can be maintained. The anonymous function returns the actual constructor that'll be called later. Each call to the constructor copies the current value of the counter to the "id" property of the new object, and increments it.
Keep in mind as you're learning about JavaScript inheritance that there's really no direct equivalent to the concept of "Class" in languages like C# or Java. Attempts to make JavaScript act like those languages almost always end in frustration and heartbreak.
Upvotes: 2