Friday, January 3, 2014

improving encapsulation with a singleton pattern in js

A while back I blogged about a simple javascript singleton pattern. Recently at work I got called on the fact that it was doing a bad job at encapsulation, specifically there was nothing like public/private functions in it, even though I was implementing an API with functions that might as well have been private, for clarity purposes.

The core pattern was something like
var someObject = new function(){
    this.someVariable = undefined;

    this.init = function(){
        alert("started up");
        someObject.someVariable = true;
    };
}
The slight variant goes like this
var someObject = new function(){
    var somePrivateVariable = null;
    var somePrivateFunction = function(){
        alert('shh');
    }
    this.somePublicVariable = null;
    this.somePublicFunction = function(){
        alert(somePrivateVariable); //still has access because of function level scoping
        somePrivateFunction();
    }
}

Now the outside world has access to the public things but not the private ones.


No comments:

Post a Comment