Reputation: 21278
I have a problem I need to solve regarding my Javascript code. When instantiating object (in this case adding new members) I want the members to get unique ids. Below is a simplified version of my code to give you a picture of what I want. What is the best way to do this?
function Member(name){
//unique id code...
this.getName = function(){
return name;
}
this.setName = function(_name){
name = _name;
}
}
Upvotes: 1
Views: 3299
Reputation: 821
Use an immediately invoked function expression (IIFE) that creates a scope for a function. In this scope you define a counter variable. This scope is preserved throughout runtime as long as uniqueId exists. Only the returned function has access to the scope. Each time you call your uniqueId function it adds +1 to the counter in the scope and returns the value.
var uniqueId = (() => {
var counter = 0
return function() {
return counter++
}
})()
console.log(uniqueId())
console.log(uniqueId())
console.log(uniqueId())
Hint: lodash has a uniqueId function also.
Upvotes: 1
Reputation: 7579
If you just want a (probably) unique id, you could use
var id = new Date().getTime();
which returns milliseconds since epoch (January 1st 1970).
EDIT: I guess I've never encountered those extreme situations described in the comments below in a javascript application, but in those cases this certainly is a bad solution.
Upvotes: 1
Reputation: 236122
I guess its easy as:
(function() {
var idcounter = 0;
function Member(name){
this.id = idcounter++;
this.getName = function(){
return lastName;
};
this.setName = function(_name){
name = _name;
};
}
yournamespace.Member = Member;
}());
yournamespace should be your application object or whatever. You also could replace it with window
in a browser, to have the Member
constructor global.
Upvotes: 3