Closure in Javascript - Revisiting Counter Example

artydev - Aug 30 '23 - - Dev Community

In my precedent post I presented an example which was not optimal.

A nice suggestion from Eckehard leaded me to the new version, which is more better as it does not create 'hidden global variables' when using "id's"...

The idea is to not use any external libraries.

ClosureRevisited

function Counter () {
  let count = 0
  let eltCreate = (tag) => document.createElement(tag)
  function View () {
    let alltags = ["div", "h3", "button", "button"]
    let [div, h3, btninc, btndec] = allElts = alltags.map(eltCreate)
    let incby = (incer) => () => h3.innerText = +h3.innerText + incer
    allElts.slice(1).forEach(child => div.append(child))
    h3.innerText = count
    btninc.innerText = "INC"; btninc.onclick = incby(1) 
    btndec.innerText = "DEC"; btndec.onclick = incby(-1)
    return div
  }
  return View ()
}
[...Array(5)].forEach(() => document.body.append(Counter()))  

Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player