0

Looking at this implementation of a 'Singleton' in Javascript (something I've been playing with please correct me if I'm wrong), what exactly is the closure?

As far as I understand from reading the "You Don't know JS" book on scope and closures, the correct terminology would be to say: Function (or module) M1 has closure over the main scope.

To describe this, I would say that M1 creates a private scope within the main object. The conceptual boundary between these two scopes is considered a 'closure'.

But it would seem to me that in order to be a closure (and not just a function with a private scope), you need an interface accessible within the scope that you are 'closing off' that gives you access to the private scope.

i.e. it would seem to me that you could you say a closure is defined by making variables within a private scope available to the respective 'public' scope even after control has been handed back to the 'public' scope after executing the function creating a closure.

Is the above correct?

/**
 * Singleton object implementation
 */
var M1 = (function() {

    // Private variables
    var items = [];
    var x = 5;

    // Getters and setters
    var getX = function() {return x;};
    var getItems = function() {return items;};

    // Private functions
    var item = function(name) {
        this.name = name;
    };

    // Public interface
    return {
        getX: getX,
        getItems: getItems,
        createItem: function(name) {
            items.push(new item(name));
        }
    };
})();
Zach Smith
  • 8,458
  • 13
  • 59
  • 133
  • I would think this perhaps belongs at codereview? – mplungjan Feb 06 '16 at 06:28
  • 1
    Yes your statements are correct, take a look at this answer: http://stackoverflow.com/a/7464475/3393666 , it illustrates and says the same as you but in other words. – kevinkl3 Feb 06 '16 at 06:33
  • The accepted answer in that question refers to the private variables being closed over. I thought it was the public scope being closed over by the private scope. Which is more correct? – Zach Smith Feb 06 '16 at 06:47
  • @mplungjan This is a question seeking understanding of principles, not open-ended critique. The code presented here is of a generic / hypothetical nature, and this question would be off-topic on Code Review. – 200_success Feb 06 '16 at 07:54
  • 1
    The paragraph after "i.e." pretty much sums it up. According to most, the closure is created when the function's execution context is created. At that point, it "closes over" the outer execution contexts. However, it's the ability of "privileged" functions to access the inner scope that makes closures interesting. – RobG Feb 06 '16 at 12:32

0 Answers0