Javascript Simple Closure Pattern

Simple Closure Pattern

There has been lots of discussion about closures over the years especially since the success of popular frameworks such as JQuery and other such. But how are such patterns created and what are some interesting things that we can do with contexts?

var MyObject=(function(){
    var _this={
	    getLength:function(){

	    },
        toString:function(){

        },
        render:function(){

        }
    };
    return _this;
})();

The previous pattern is a very small object that is self instantiating, which means that new doesn&squo;t have to be called in order to create the object. The object of course may be difficult to reproduce however.This pattern however, does allow for some interesting possibilities in regards to private members but lacks the ability to initialize.

var MyObject=(function(){
    var _internal = null;
    var _this={
        init:function(internal){
            _internal = internal;
        },
        getInternal:function(){
            return _internal;
        },
        toString:function(){
            return "My Object" ;
        },
        render:function(){
        }
    };
    return _this;
})();
MyObject.init("Internal");
alert(typeof(MyObject._internal));
alert(typeof(MyObject.getInternal()));
ttessier

About ttessier

Professional Developer and Operator of SwhistleSoft
This entry was posted in Javascript Development, Web Development and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *