klenwell information services : JavascriptStyleGuide

Revision [2759]

This is an old revision of JavascriptStyleGuide made by KlenwellAdmin on 2014-06-15 22:11:33.
 

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 BrowserCache = (function() {
  var ENGINE = localStorage;

  var setValue = function(key, value) {
    var jsonValue = JSON.stringify(value);
    ENGINE.setItem(key, jsonValue);
  };

  var getValue = function(key) {
    return JSON.parse(ENGINE.getItem(key));
  };

  // Public API
  var publicAPI = {
    set: setValue,
    get: getValue
  }

  return publicAPI;
})();