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));
}
};
})();