Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing object id automatically JS constructor (static method and variable)

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.

like image 486
fheoosghalzr Avatar asked Dec 30 '25 01:12

fheoosghalzr


1 Answers

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}

```

like image 121
Michael Prokopowicz Avatar answered Dec 31 '25 16:12

Michael Prokopowicz