Created
October 22, 2014 02:02
-
-
Save bahmutov/64a0dd821dfb97d97066 to your computer and use it in GitHub Desktop.
Module pattern using anonymous constructor function expression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
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