Friday, April 18, 2014

more improvements to object like encapsulation in js

An improvement to what I wrote about here-- I was still thinking in terms of a singleton pattern, but I think it can be easily extended to be reusable:

With a setup
function someObject(init){
    var somePrivateVariable = init;
    var somePrivateFunction = function(){
        alert('shh');
    }
    this.somePublicVariable = null;
    this.somePublicFunction = function(){
//still has access because of function level scoping
        alert(somePrivateVariable); 
        somePrivateFunction();
    }
}

You can make multiple instances

        var m = new someObject(1);
        var n = new someObject(2);
        m.somePublicFunction();
        n.somePublicFunction();

No comments:

Post a Comment