krulik
7/11/2015 - 11:16 PM

JavaScript Class pattern.markdown

@import "compass/css3";

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
function log (message) {
  var div = document.createElement("div");
  div.textContent = message;
  document.body.appendChild(div);
}


var Foo = (function (Foo) {
  
  // Constructor
  var Foo = function () {
    this.publicInstanceOnly = Math.random();   
  };
  
  function privateStaticMethod (num) {
    return parseInt(num * 1000);
  }   
  
  // Private methods which assume "this" to be Foo.
  // Don't get re-defined when using "new".
  var methods = {
    id: Math.random(),
    sharedInstanceMethod: function () {
      var result = privateStaticMethod(this.publicInstanceOnly);
      log(result);
    },
    bind: function (instance) {
      return $.extend(true, {}, instance, methods)
    }
  };    
  
  function _ () {
    var instance = arguments[0];
    return $.extend(true, {}, instance, methods);
  }
  
  Foo.prototype.apiMethod = function () {
    
    // Way 1
    methods.sharedInstanceMethod.call(this);
    
    // Way 2
    var _this = _(this);
    _this.sharedInstanceMethod();
    
    // Way 3
    var $this = methods.bind(this);    
    log($this.id);
  };
  
  return Foo;
  
}(Foo));

var f1 = new Foo();
var f2 = new Foo();
log("f1");
f1.apiMethod();
log("f2");
f2.apiMethod();

log("test");
f1.sharedInstanceMethod();