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

给你一囗甜甜゛ 提交于 2019-12-12 18:18:57

问题


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.


回答1:


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}

```




回答2:


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


来源:https://stackoverflow.com/questions/33554120/incrementing-object-id-automatically-js-constructor-static-method-and-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!