DesignFestival: One JavaScript Design Pattern I Can’t Live Without

Tweet

I thought it might be interesting to look at a JavaScript design pattern that I use a great deal. I settled on it gradually, over a period of time, absorbing and adapting influences from various sources, until reaching a pattern that offers the flexibility I need. Let me show you an overview, and then look at how it comes together: function MyScript(){} (function() var THIS = this; function defined(x) return typeof x != ‘undefined'; this.ready = false; this.init = function() this.ready = true; ; this.doSomething = function() ; var options = x : 123, y : ‘abc’ ; this.define = function(key, value) if(defined(options[key])) options[key] = value; }; }).apply(MyScript); As you can see from that sample code, the overall structure is a function literal: (function() … )(); A function literal is essentially a self-executing scope, equivalent to defining a named function and then calling it immediately: function doSomething() { …

View post:
DesignFestival: One JavaScript Design Pattern I Can’t Live Without

Free Chapter! HTML5 & CSS3 for the Real World

Get a free chapter of SitePoint's new book, the second edition of our popular HTML5 & CSS3 for the Real World and receive updates on our latest offers.

No Reader comments