Skip to content

Instantly share code, notes, and snippets.

@bahmutov
Created October 22, 2014 02:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bahmutov/64a0dd821dfb97d97066 to your computer and use it in GitHub Desktop.
Save bahmutov/64a0dd821dfb97d97066 to your computer and use it in GitHub Desktop.
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
Copy link

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
Copy link

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