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 book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

No Reader comments