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

James Edwards
James is a freelance web developer based in the UK, specialising in JavaScript application development and building accessible websites. With more than a decade's professional experience, he is a published author, a frequent blogger and speaker, and an outspoken advocate of standards-based development.

No Reader comments

Stay ahead of the game Exclusive content for developers and digital experts Go Premium