Reputation: 681
I would like to write a student class with an id attribute
when I new objects like this:
var s1 = new Student()
var s2 = new Student()
var s3 = new Student()
I can get this result:
console.log(s1.id) //1
console.log(s2.id) //2
console.log(s3.id) //3
Upvotes: 1
Views: 56
Reputation: 1404
You could do this with either a global variable or a static variable (The latter is preferred). This means that the variable belongs to the type rather than the instance.
function Student(){
this.id = Student.currentId;
Student.currentID++;
}
Student.currentID = 1;
Upvotes: 2
Reputation: 10972
var Student = (function() {
var id = 0;
return function Student() {
this.id = ++id;
};
})();
Here every new Student
object will get an incremented id
from the var id
that is in the outer IIFE.
The IIFE part isn't strictly needed, but it protects the var id
from being accidentally modified by other code. Without the IIFE, it would simply be:
var id = 0;
function Student() {
this.id = ++id;
}
But the var id
can be reached by any code in the enclosing scope, so the first example is safer.
Upvotes: 4