My Favorite JavaScript Design Pattern

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()
{
  ...
}

doSomething();

I originally started using function literals for the sake of encapsulation—any script in any format can be wrapped in that enclosure, and it effectively “seals” it into a private scope, preventing it from conflicting with other scripts in the same scope, or with data in the global scope. The bracket-pair at the very end is what executes the scope, calling it just like any other function.

But if, instead of just calling it globally, the scope is executed using Function.apply, it can be made to execute in a specific, named scope which can then be referenced externally.

So by combining those two together—the creation of a named function, then the execution of a function literal into the scope of the named function—we end up with a single-use object that can form the basis of any script, while simulating the kind of inheritance that’s found in an object-oriented class.

The Beauty Within

Look at that first code example, and you can see what flexibility is offered by the structure of the enclosing scope. It’s nothing you can’t do in any function, of course, but by wrapping it up in this way we have a construct that can be associated with any named scope.

We can create multiple such constructs, and associate them all with the same scope, and then all of them will share their public data with each other.

But at the same time as sharing public data, each can define its own private data too. Here for example, at the very top of the script:

var THIS = this;

We’ve created a private variable called THIS which points to the function scope, and can be used within private functions to refer to it—exactly the same trick as going "self = this" to create a reference for inner scopes.

Other private variables, declared the same way, can share the uppercase convention if they define constant data (however declaration using const instead of var should be avoided, because it’s not well-supported).

Private functions can be used to provide internal utilities:

function defined(x)
{
  return typeof x != 'undefined';
}

Then we can create public methods and properties, accessible to other instances, and to the outside:

this.ready = false;

this.init = function()
{
  this.ready = true;
};

this.doSomething = function()
{
};

We can also create privileged values—which are private, but publicly definable, in this case via the public define method; its arguments could be further validated according to the needs of the data:


var options = {
  x : 123,
  y : 'abc'
  };

this.define = function(key, value)
{
  if(defined(options[key]))
  {
    options[key] = value;
  }
};

Wrapped Up!

All of these features are what makes the construct so useful to me. And it’s all wrapped up in a neat, self-executing singleton—a single-use object that’s easy to refer-to and integrate, and straightforward to use!

So what do you think? Is this a pattern that’s familiar to you, or do you have something else you like to use?

Thumbnail credit: superkimbo

note:Want more?

If you want to read more from James, subscribe to our weekly tech geek newsletter, Tech Times.

Win an Annual Membership to Learnable,

SitePoint's Learning Platform

  • Demis

    What benefit does this have over the module pattern?

  • goldfidget

    This is rather cool.

  • http://www.brothercake.com/ James Edwards

    You’ll have to be more specific ..?

    • Poetro

      In terms of module patterns the one above would look like:
      function MyScript(){
      var that = this,
      options = {
      x : 123,
      y : ‘abc’
      };
      function defined(x) {
      return typeof x !== ‘undefined';
      }
      this.ready = false;
      this.init = function() {
      this.ready = true;
      };
      this.doSomething = function() {
      };
      this.define = function(key, value) {
      if(defined(options[key])) {
      options[key] = value;
      }
      };
      }
      ps: btw how do you format code in comments? Nothing about this in FAQ or here in the comment form.

    • Ben Truyman
  • Justen

    I used to use a pattern very similar to this but eventually I decided it was overly cumbersome and stopped bothering. I do like the “THIS = this” workaround, which I never discovered. These days I prefer to just write better code and maintain knowledge of scope and naming. My server-side code only ever delivers the javascript actually needed on a page anyway so I have never run into toe-stepping. Anything I intend to use broadly or release to the public I develop as a plugin to an existing framework (usually jquery) so I don’t run into too much trouble there either.

  • neil_g

    Hi James,

    This is a topic I’m interested in learning more about. Could you provide an example of a script written this way? Perhaps one that prints “hello world!” or something equally simple? I tend to have trouble wrapping my brain around sample code that is purely abstract.

    Thanks so much!

    Great article!

  • mark

    ever heard of jsLint ? http://www.jslint.com/

  • Dan

    In the apply, I like the parameter that’s never passed as a means of checking an undefined variable (because real undefined can be overwritten) instead of your typeof check. I also like to pass in window.document as a variable (doc) which helps minification. Ps this comment box is too small on the iPhone.

  • Karl Oakes

    Interesting alternative to the Module pattern…
    I tend to write Singleton object wrapped up in a self executing anon function using the Module or the Revealing module pattern
    http://www.wait-till-i.com/2007/08/22/again-with-the-module-pattern-reveal-something-to-the-world/
    to provide a public API to my object instead of privileged methods.
    I like the ‘THIS’ concept as constant data, I always use ‘that’ to reference my object when the context has changed, i.e. event handlers. Always good to see other patterns as it helps to question your own implementations and learn from others, thanks…

    By the way you have typo on line 10
    this.init = function(
    should be
    this.init = function()

  • Nico

    Hi,
    Is there a reason why MyScript should be a function ?
    Why not just a simple object ?
    Is there a reason to declare the MyScript variable outside the local scope ? It’s possible to define a global variable form within a local scope, no ?
    Here is an example of the same thing, but my way :
    (function(window, Array, undef) {
    function init() {
    this.ready = true;
    }
    function doSomething() {

    }
    function define() {
    if(options[key] !== undef && (key !== ‘aList’ || value instanceof Array)) {
    options[key] = value;
    }
    }
    var options = {
    x : 123,
    y : ‘abc’,
    aList : []
    },
    MyScript = {
    ready : false,
    init : init,
    doSomething : doSomething,
    define : define
    };
    window.MyScript = MyScript;
    }(this, this.Array));
    And it’s possible to make it shorter using less local variables (but I prefer the first version, I find it clearer) :
    (function(window, Array, undef) {
    var options = {
    x : 123,
    y : ‘abc’,
    aList : []
    },
    MyScript = window.MyScript = {
    ready : false,
    init : function () {
    this.ready = true;
    },
    doSomething : function () {

    },
    define : function define() {
    if(options[key] !== undef && (key !== ‘aList’ || value instanceof Array)) {
    options[key] = value;
    }
    }
    };
    }(this, this.Array));

    What about this pieces of code ?

    • Karl Oakes

      Hi Nico…This is just another approach to the Revealing module pattern and would very similar to my own implementation. I would normally just return the public object instead of passing and assigning to the window object , same thing though…

  • Barney

    Hiya James,

    Like a lot of people, I think terse Javascript scoping methodologies are awesome out of principle. However, the quick variable scope references via THIS/this, and your reference to ‘publicly defining private members’, throw me a bit.

    As with a lot of “let’s make Javascript more like classic object-oriented languages”, it becomes very difficult to extract the true power and the reasons for the conventions without examples — I’d really like to see an even slightly abstracted example of HOW you used this, WHY, and WHAT it achieved (while avoiding pitfalls X Y Z).

    Not having a dig, but the recent surge in popularity of anonymous functions and inheritance methods without the authors explaining succinctly why or how one would want to work this way … is responsible for some dubious developments in the culture of Javascript-writing in the mid-level: while conflicting namespaces are a pain to resolve and iterative, single-scope JS frameworks can lead to incredibly verbose methodologies, none of this is worse than mid-level front-enders writing everything in inaccessible closures, creating huge descendant objects using inflexible constructors, with all sorts of misguided inheritance, for the wrong reasons — ie because they saw John Resig do it and it challenged them — not because it’s in any way appropriate to the tasks at hand.

    Maybe a follow-up post with an example of problematic code, re-written with this method in a simple how-to?

    BTW: I believe line 10 is missing a closing parens.

    • Chris May

      James, thank you for sharing your favorite pattern. I really appreciate the opportunity to peek inside the mind of an experienced developer.

      But I must say, I agree with Barney. I would really appreciate some more depth about why you code this way, especially with the specific things you included in your post.

      Thank you for your follow-up article (can there be a link from this post?) that explains a tiny bit more about your decisions, but I will be disappointed if the reason why there aren’t more answers to these comments is to break up one excellent, explanatory post (in the style of A List Apart) into many individual posts over several weeks.

      (And the code still has the missing closing parenthesis in line 10… Is it a practice for SitePoint to update their posts after they are published?)

  • t

    very dirty

  • listenrightmeow

    Your structure is pretty much a javascript class. Why the elaborate workaround?

  • Giovanni

    Thank you for the interesting post, James.
    Inside the init() function you are using ‘this’ instead of ‘THIS':

    this.init = function(
    {
    this.ready = true; //Why not THIS.ready = true ?
    };

    Any particular reason why you are not using ‘THIS’?