Created
March 11, 2011 18:38
-
-
Save benjisg/866343 to your computer and use it in GitHub Desktop.
JavaScript Module Pattern
This file contains hidden or 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
// 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