klenwell information services : JavascriptStyleGuide

JavaScript Style Guide


Augment Pattern

Object-oriented classes requiring classical inheritance should use the augment pattern:

function augment(parent, properties) {
  var child = properties.constructor || function() {
    return parent.apply(this, arguments);
  };

  var Surrogate = function(){ this.constructor = child; };
  Surrogate.prototype = parent.prototype;
  child.prototype = new Surrogate;

  for (var key in properties) {
    child.prototype[key] = properties[key];
  }

  return child;
};


var MinObject = augment(Object, {

  constructor: function(debug) {
    this.debug = (debug !== undefined) ? debug : false;
    this.logDebug('init MinStateMachine with state:', this.state);
  },

  logDebug: function() {
    if ( this.debug ) {
      var args = Array.prototype.slice.call(arguments, 0);
      console.debug(args.join(' '));
    }
  },

});


Module Pattern

Modules should use the jQuery module pattern:
var MinFoo = (function() {

  var self = {};

  var init = function(foo) {
    self.foo = foo;
  };

  var foo = function() {
    console.debug('foo', self.foo);
  };

  // Public API
  var publicAPI = {
    init: init,
    foo: foo
  }

  return publicAPI;
})();

MinFoo.init('hello');
MinFoo.foo();