32030

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.

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

Recommend

  • How to populate mongoose with a large data set
  • add/remove multiple input fields
  • How do you close open files using Swift?
  • Assigning int value to string
  • How do I run a function on a specific key press in JavaFX?
  • Gradle dynamic flavor
  • Getting org.testng.TestNGException: No free nodes found in:[DynamicGraph Exception
  • Stack Cards horizontally with some offset
  • Function calling incorrect values
  • is there a way in autoit script to find if current file was included or it is running on its own?
  • Guava how to copy all files from one directory to another
  • SQL - Select lowest values with group by and order by?
  • Cypher - matching two different possible paths and return both
  • How to display special characters in SQL server 2008?
  • how does System.Web.HttpRequest::PathInfo work?
  • Not able to aggregate on nested fields in elasticsearch
  • Insert new calendar with SyncAdapter- Calendar API Android
  • Django simple Captcha “No module named fields” error
  • Caching attributes in superclass
  • print() is showing quotation marks in results
  • Functions in global context
  • formatting the colorbar ticklabels with SymLogNorm normalization in matplotlib
  • Different response to non-authenticated users and AJAX calls
  • C# - Serializing and deserializing static member
  • Bug in WPF DataGrid
  • Do create extension work in single-user mode in postgres?
  • Akka Routing: Reply's send to router ends up as dead letters
  • AT Commands to Send SMS not working in Windows 8.1
  • How to delete a row from a dynamic generate table using jquery?
  • json Serialization in asp
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • Free memory of cv::Mat loaded using FileStorage API
  • How do I configure my settings file to work with unit tests?
  • How to stop GridView from loading again when I press back button?
  • Is it possible to post an object from jquery to bottle.py?
  • unknown Exception android
  • Django query for large number of relationships
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • How can I use `wmic` in a Windows PE script?
  • How to push additional view controllers onto NavigationController but keep the TabBar?