Question

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;
    }
}
Was it helpful?

Solution

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.

OTHER TIPS

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.

Use a 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top