JSFiddle - React, Tailwind, and code Playground

by chridam

JavaScript

// Define the Employee constructor
function Employee(firstName) {
  this.firstName = firstName;
}

// Add a getId method to Employee.prototype to get a unique ID, based on the closure http://chamnapchhorn.blogspot.com/2008/07/trick-to-use-static-variables-in.html
Employee.prototype.getId = (function() {
   var id = 1; // This is the private persistent value
   // The outer function returns a nested function that has access
   // to the persistent value.  It is this nested function we're storing
   // in the variable uniqueID above.
   return function() { return id++; };  // Return and increment
})(); // Invoke the outer function after defining it.


// Example usage:
var emp1 = new Employee("foo");
var emp2 = new Employee("bar");

// Check that getId() method works correctly
alert(emp1.getId());  // 1 
alert(emp2.getId());  // 2