
I am newbie in JavaScript, I have an idea, to create class (function), I know how it works in JS (prototypes and so on), but I need to do something like incrementing Id in databases.
My idea is to create static method, I think closure will suit great here and whenever new object is created it should return incremented id.
I don't know what is the right way to implement this, or maybe this is bad practice.
Please provide simple example.
Answer1:
Closure is a good idea:
var MyClass = (function() {
var nextId = 1;
return function MyClass(name) {
this.name = name;
this.id = nextId++;
}
})();
var obj1 = new MyClass('joe'); //{name: "joe", id: 1}
var obj2 = new MyClass('doe'); //{name: "doe", id: 2}
Or, if you want some more flexible solution you can create simple factory:
function MyObjectFactory(initialId) {
this.nextId = initialId || 1;
}
MyObjectFactory.prototype.createObject = function(name) {
return {name: name, id: this.nextId++}
}
var myFactory = new MyObjectFactory(9);
var obj1 = myFactory.createObject('joe'); //{name: 'joe', id: 9}
var obj2 = myFactory.createObject('doe'); //{name: 'doe', id: 10}
```
Answer2:
Since node is single threaded this should be easy and relatively safe to do.
I think you could accomplish this by creating a global variable
global.counter = 0
Then on construction your class could increment it, or increment and grab the value if you need to keep reference to the value when the class was created.
function YourClass() {
global.counter++;
}
var yc = new YourClass(); // global.counter 1
var yc2 = new YourClass(); // global.counter 2