user3871
user3871

Reputation: 12718

relevance and use for closures vs namespacing

The answer in this question on closures states the importance of closures is "Because javascript doesn't have feature like namespaces, and you can mess up pretty easily with all sort of global objects." And msn guide describes it as "lexical scoping."

And this question paints very clearly the difference between namespacing and closures...

So I'm wondering, if Javascript actually does have namespacing, which I use commonly, what is the use for closures nowadays? I simply don't see the need to close off variables with closure lexical scoping when I can organize and use them via namespaces.

Upvotes: 0

Views: 62

Answers (1)

Quentin
Quentin

Reputation: 944114

JavaScript doesn't have namespacing in the traditional sense. That's just a term used to describe organising the functions of a library in an object structure.

Closures are useful because libraries often want to store state in variables without needing to expose those variables to any other code.

If that data was exposed on the namespace object then it would be harder for a user of the library to tell which properties were designed to be interacted with and which were for internal use only.

Consider for example:

var example_namespace = (function() {

  var interval;
  var element;

  function start() {
    if (interval) {
      return;
    }

    if (!element) {
      element = document.querySelector('span');
    }

    interval = setInterval(increment, 500);
  }

  function stop() {
    clearInterval(interval);
    interval = null;
  }

  function increment() {
    element.innerHTML++;
  }

  return {
    counter: {
      start: start,
      stop: stop
    }
  };
}());

addEventListener('load', function() {
  document.querySelector('#start').addEventListener('click', example_namespace.counter.start);
  document.querySelector('#stop').addEventListener('click', example_namespace.counter.stop);
});
Count:
<span>0</span>

<button type="button" id="start">start</button>
<button type="button" id="stop">stop</button>

Without using a closure, interval, element, and increment would all be exposed on the namespace object or globals.

Upvotes: 1

Related Questions