Performance Zone is brought to you in partnership with:

Leigh has been in the technology industry for over 15 years, writing marketing and technical documentation for Sun Microsystems, Wells Fargo, and more. She currently works at New Relic as a Marketing Manager. Leigh is a DZone MVB and is not an employee of DZone and has posted 106 posts at DZone. You can read more from them at their website. View Full User Profile

Two of My Favorite Javascript Design Patterns

10.10.2012
| 8553 views |
  • submit to reddit

The content of this article was originally written by David Morrow over at the New Relic blog.

So you write JavaScript. That’s pretty much a given for today’s modern web apps. Unfortunately, JavaScript doesn’t always get the organization it deserves and ends up being a procedural mess of jQuery on ready statements.

In this post, I’m going to show you two of my favorite patterns for keeping JavaScript well organized. But before I do, let’s go over a few prerequisites.

Namespace Your Code
One of the worst and most common JavaScript mistakes is assigning variable onto the global namespace (aka ‘window’) if you’re running JavaScript in a browser. This can lead to conflicting functions between you and other developers. And is just, well, messy. The best way to avoid to do this is namespacing as shown in this example:

window.NR = window.NR || {};
window.NR.myFunction = function () {
  // your code...
};

And avoid this example:

function myFunction () {   // your code... };

Use Strict Mode
Even inside a namespaced function, there can still be a problem. You can accidentally assign variables to the global namespace. To prevent this, prefix all variable declarations with var or this.

Alternatively, you can use strict mode. As the name implies, strict mode parses your JavaScript in a much stricter format. For example, if you attempt to set a variable that is not yet defined, it will through an error instead of assigning to global / window.

If you’re interested in learning more about strict mode, check out this article on John Resig’s blog.

Lint your JavaScript
JSLint evaluates your JavaScript against Douglas Crockford’s coding suggestions. There are plugins for most of the popular editors to evaluate code including Sublime Text 2, Textmate and Vim.

The main benefits of using JSLint are:

* Your code is checked for errors before running, saving you time and debugging effort.
* Sharing linted code in a team unifies coding styles, making code more readable and consistent.

Even if you disagree with some of Douglas’s assertions about how your code should be formatted, you should still use JSLint. You can opt out of the rules with preference setting or comments on the top of your JavaScript file.

I prefer using comments because it gets parsed in the same way when another developer works on you file. This prevents you from getting conflicting parsing results when one of your teammates sets different preferences.

To give you example, here are my standard JSLint configuration setting comments:

/*global NR:true, jQuery:true, Backbone:true, $:true*/
/*jslint browser: true, white: true, vars: true, devel: true, bitwise: true, debug: true, nomen: true, sloppy: false, indent: 2*/

The global declarations tell JSLint which variables to expect on the global namespace – JQuery, Backbone, etc. If it encounters other, it will throw and error. The JSLint options determine what rules are opted into or out of. See the full list of rules on the JSLint website.

OK! Now that’s out of the way, let’s look at a couple of JavaScript patterns I commonly use.

The Module
The module pattern is great if you only need one, such as in a navigation system, and you want to be able to access the object from any scope. By convention, a module should be camelCased with a lower case first letterer.

There are many benefits and drawbacks to using the module pattern:

Pros:

* There’s no need to instantiate, just begin calling methods on it.
* It’s accessible from anywhere. There’s no need to retain a handle to your instance.
* It keeps state and variable values.

Cons:

* You can only have one. Don’t make ten of these for each type of item on the DOM or a similar situation.
* You don’t have a constructor function, so it won’t be fired automatically like with an instance.
* If you need initialization on the module, you need to call it manually the first time it’s used.

Here’s an example module:

(function () {
  "use strict";
  window.NR = window.NR || {};
  window.NR.myModule = {
    myVariable: "foo",
 
    initialize: function () {
      // your initialization code here
    },
 
    anotherMethod: function () {
      this.myVariable = "foobar";
    }
  };
}());

And here’s how it can be used:

NR.myModule.initialize();
NR.myModule.anotherMethod();
console.log(NR.myModule.myVariable);
// outputs
// "foobar"

Classes
Some people will argue that your should never use ‘new’ when working with JavaScript as there are no true classes in the language. However, I find this pattern extremely helpful for a number of reasons described below. Also, many popular frameworks such as Backbone use class instantiation / extension patterns. Naming conventions for classes is CamelCase with an upper case first letter.

Some of the benefits of this pattern are:

* It’s great for when you have many of an item and each needs its own state.
* It’s a familiar OOP pattern / workflow for many developers.
* It has a constructor function that’s immediately fired on instantiation.

But the drawbacks are:

* You have to remember to instantiate before you can use it. If you don’t, it will cause errors.
* You have to keep a handle to the instance that’s returned from the constructor.

Here’s an example class:

window.NR = window.NR || {};
window.NR.MyClass = (function () {
  "use strict";
 
  function MyClass(val) {
    this.instanceVar = MyClass.staticVar + val;
  }
 
  MyClass.staticVar = "prefix-";
  var instanceVar = "";
 
  MyClass.prototype.exampleFunction = function () {
    alert('i am an additional function');
  };
 
  return MyClass;
}());

window.NR = window.NR || {};
window.NR.MyClass = (function () {
  "use strict";
 
  function MyClass(val) {
    this.instanceVar = MyClass.staticVar + val;
  }
 
  MyClass.staticVar = "prefix-";
  var instanceVar = "";
 
  MyClass.prototype.exampleFunction = function () {
    alert('i am an additional function');
  };
 
  return MyClass;
}());

And how it can be used:

var instance1 = new NR.MyClass('class 1');
console.log(instance1.instanceVar);
 
NR.MyClass.staticVar = 'PREFIX-';
 
var instance2 = new NR.MyClass('class 2');
console.log(instance2.instanceVar);
 
// Outputs
// "prefix-class 1"
// "PREFIX-class 2"

Summary
I hope these patterns help you keep your JavaScript better organized. What other patterns do you use? Share yours in the comments below.

 

 

 

 

Published at DZone with permission of Leigh Shevchik, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)