Skip to content

Instantly share code, notes, and snippets.

@benjisg
Created March 11, 2011 18:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benjisg/866343 to your computer and use it in GitHub Desktop.
Save benjisg/866343 to your computer and use it in GitHub Desktop.
JavaScript Module Pattern
// Setup a module and use immediate invocation to run it right away
var MyModule = function() {
// Some private properties
var foo = "1";
var bar = 2;
// A private function
var updateFoo = function(value) {
foo = value;
};
// Setup some public functions
return {
giveMeFoo : function() {
return foo;
},
giveMeBar : function() {
return bar;
}
};
}();
// Try to access the internal properties
console.log(MyModule.foo); // undefined
console.log(MyModule.bar); // undefined
MyModule.updateFoo(1); // Runtime error; MyModule.updateFoo is not a function
// Use the public accessors
console.log(MyModule.giveMeFoo()); // 1
console.log(MyModule.giveMeBar()); // 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment