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

Tags: javascript, tutorial
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.

Free Guide:

How to Choose the Right Charting Library for Your Application

How do you make sure that the charting library you choose has everything you need? Sign up to receive this detailed guide from FusionCharts, which explores all the factors you need to consider before making the decision.

No Reader comments

Special Offer
Free course!

Git into it! Bonus course Introduction to Git is yours when you take up a free 14 day SitePoint Premium trial.