One JavaScript Design Pattern I Can’t Live Without

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() { ... })();[/xml]
A function literal is essentially a self-executing scope, equivalent to defining a named function and then calling it immediately:
1function 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

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.

  • Owen Savill

    You have a typo
    “this.init = function(” should be “this.init = function()”

  • http://hanleybrand.com Peter Hanley

    I like this pattern, although I’d suggest that even as an example, “THIS = this;” is going to confuse some readers, and will mess anybody up at some point.

    Since variable names are a bit of secret fun, and you’re using THIS for function scope: consider changing it to “FTHIS = this” :)

    After I made my Fb comment, it occurred to me that if someone is bothering to do this, they might want to go ahead and namespace their javascript…

    //this uses jquery for the loadpage function

    var DF = {

    // variables are just properties, and can be referenced via Namespace.propName, e.g. DF.num

    number: "123",
    userName: "Julie Ahange"

    // functions are also properties, this can be executed via DF.loadPage()

    loadPage: function(){
    $('#tabOrg').load('someDynamic.cgi?' + DF.userName);
    },

    }

    // end of name space, begin javascript that makes stuff happen

    $(function() {
    //execute dynamic content load

    DF.loadPage();
    });

    The main advantage to me is that it provides a clearer code, because it makes plain what code originates from my project and what originates from jquery, a plug-in or what have you.

    Great article!

  • Abc

    cool!

  • http://www.debcom-software.com Web Developer India

    Effective post on java-script design pattern.  Already I implemented.
     
    Thanks james.

  • Jesse Williamson

    Intrigued…completely lost, but very intrigued. I obviously need to step my JavaScript game up. Going to need to read and read again; love it when that happens.

  • Guest

    It would be nice if you had some formatting in the code. It’s hard to read without any line breaks.

  • Elijah Madden

    Good introduction. You should try using something like jsfiddle or codemirror to display your code snippets. Syntax highlighting and whitespace can do a lot for readability. 

  • http://www.chrisupjohn.me Chris Upjohn

    Nice post James, i have seen this design pattern before but never really got into it just because i have my own style. Maybe one day soon i can adapt this pattern permanently into my everyday development.

  • Josh

    Thank you for your insight. I agree though could you apply some code formatting, it’s hard to read otherwise.

  • Todd Fiske

    I agree with others that some line breaks and indentation would help show what’s going on. I formatted it for my own understanding, and am _pretty sure_ I got it right. =) It would also be great to see a basic example of how this would be used, for us JavaScript advanced novices.

  • Joshnaro

    I tend to use the prototype paradigm for object oriented JavaScript. You get inheritance and multi-use out of it:

    var MyAlertClass = function (x, y, z) {
      if (arguments.length > 0) {
        this.className = ‘MyAlertClass’ + z;
        var validateParam = function (param) {
          if (param == undefined) {
            throw new Error(‘Error message’);
          } else {
            return param;
          }
        }
        this.publicX = validateParam(x);
        this.publicY = validateParam(y);
      }
    };

    MyAlertClass.prototype.SendAlert = function (alertMessage) {
      alert(this.className + ‘ says “‘ + alertMessage + ‘”.’);
    };

    MyAlertClass.prototype.SendAlertX = function () {
      this.SendAlert(this.publicX);
    };

    var MyInheritedClass = function (x, y, z, a) {
      this.additionalPublicProperty = a;
      MyAlertClass.call(this, x, y, z);
    }

    MyInheritedClass.prototype = new MyAlertClass();
    MyInheritedClass.prototype.constructor = MyInheritedClass;

    MyInheritedClass.prototype.SendAlertY = function () {
      this.SendAlert(this.publicY + ‘ and ‘ + this.additionalPublicProperty);
    };

    var randomFunctionSomewhere = function () {

      var myAlertClassInstanceA = new MyAlertClass(‘Hello World’, 123, ‘A’);
      var myAlertClassInstanceB = new MyAlertClass(‘World’, ‘abc’, ‘B’);
      var myInheritedClassA = new MyInheritedClass(‘X’, ‘Y’, ‘Z’, ‘Additional Property’);

      myAlertClassInstanceA.SendAlertX();
      myAlertClassInstanceB.SendAlert(myAlertClassInstanceA.className + ‘ says Hello ‘ + myAlertClassInstanceA.publicX);
      myInheritedClassA.SendAlertY();
    };

    randomFunctionSomewhere();

  • Smola

    Great post. But how are there two comments posted 6 months ago if this post was made 7 days ago (from the date of this comment?)

  • Benkert Dirk

    Hi,

    interesting construct, but i dont really like it.
    What i dislike most is, that the private methods and variables look, when called like public, global methods and variables and i think that is very confusing when you have larger amounts of Javascript code.

    Regards
    Dirk

  • https://launchpad.net/~tim.timwahrendorff rakete

    I don’t get why and how this Pattern is easy and beautiful to use whatfor? I don’t even get what you want to communicate. I feel like in Uni were we got 20 solutions but never a problem to solve.

    I read it 3 times and still don’t get the point of the article. I feel dumb now, please explain… :/

    Until then I stick with prototype.