Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Module pattern using anonymous constructor function expression
var calc = new function () {
this.add = function add(a, b) { return a + b; };
this.sub = function sub(a, b) {
return this.add(a, -b);
};
};
console.log(calc.add(2, 3)); // 5
console.log(calc.sub(2, 3)); // -1
var subtract = calc.sub;
console.log(subtract(2, 4)); // exception: this.add is undefined
@peterldowns

This comment has been minimized.

Copy link

commented Oct 22, 2014

var Calc = new function() {
  // Inside the immediately-evaluated constructor, define functions as normal
  // variables. Could also use the alternate `function add(a, b) {...}` syntax.
  var add = function(a, b) {
    return a + b;
  };
  var sub = function(a, b) {
    return add(a, -b);
  };

  // At the bottom of the constructor, set all functions / variables to be
  // exported as attributes on `this`. I generally assign `this` to the
  // module's name as a variable here to make it clear.
  var Calc = this;
  Calc.add = add;
  Calc.sub = sub;
};

console.log(Calc.add(2, 3)); // 5
console.log(Calc.sub(2, 3)); // -1

var subtract = Calc.sub;
console.log(subtract(2, 4)); // -2
@peterldowns

This comment has been minimized.

Copy link

commented Oct 22, 2014

I haven't found a name for this pattern anywhere but it's my preferred method of module/namespace definition. Also, I found this blogpost which shows that you can pass arguments just like with the (function(window,undefined){...})(window); construct:

var Module = new function(window, undefined) {
  var checkup = function() {
    return [window, undefined];
  };

  var Module = this;
  Module.checkup = checkup;
}(window);

console.log(Module.checkup()); // [Window, undefined]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.