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.
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}
```
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With