Question

I'm trying to create a counter via a closure using javascript for all links clicked on a page. This is what I have so far, but it is using a global variable. How do I modify this, using a closed variable?

var count = 0;
$('body').on('click', '.a', function() {  
    count++;
    console.log(count)
})
Was it helpful?

Solution

You can create an IIFE around it:

(function(){ 
  var count = 0;
  $('body').on('click', '.a', function() {  
    count++;
    console.log(count)
  });
})();

Javascript has function scoping, so count will be local to that outer anonymous function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top