Skip to content

Instantly share code, notes, and snippets.

@ajaxray
Last active March 23, 2016 14:48
Show Gist options
  • Save ajaxray/343f9c931158f2f4541c to your computer and use it in GitHub Desktop.
Save ajaxray/343f9c931158f2f4541c to your computer and use it in GitHub Desktop.
Sample implementation of JavaScript module pattern to explain private and public members.
var Talkative = ( function( w, $ ) {
// this object is used to store private variables and methods across multiple instantiations
var privates = {
"secret" : 'Not to share'
};
// A shared private method
privates.talk = function (msg) {
w.alert('whisper : ' + msg);
};
function Watchlist() {
// A public method
this.bigTalk = function bigTalk() {
w.alert( 'Big Talk!' );
};
// Public method using private variable
this.accessSecret = function accessSecret() {
w.alert( privates.secret );
};
// Public method using private function
this.accessPrivetTalk = function accessPrivetTalk() {
privates.talk('Private Talk');
};
}
return Watchlist;
} )( window, $);
var whoever = new Talkative();
whoever.bigTalk();
whoever.accessSecret();
whoever.accessPrivetTalk();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment