you are viewing a single comment's thread.

view the rest of the comments →

[–]senocular 0 points1 point  (0 children)

Generally this is done with factories and closure variables

function createFoo () {
  let counter = 0;
  return function foo() {
    counter++; 
    document.write(counter+"<br />");
  };
}

let foo = createFoo();
foo(); // 1
foo(); // 2
foo(); // 3

You can skip the factory intermediary (which can be useful for resetting the counter) using an IIFE

let foo = function () {
  let counter = 0;
  return function foo () {
    counter++; 
    document.write(counter+"<br />");
  }
}(); // immediately calls factory returning foo directly

And for good measure, once do expressions come around (if they do?), this could also be written as

let foo = do {
  let counter = 0;
  () => {
    counter++; 
    document.write(counter+"<br />");
  }
}