Last active
March 23, 2016 14:48
-
-
Save ajaxray/343f9c931158f2f4541c to your computer and use it in GitHub Desktop.
Sample implementation of JavaScript module pattern to explain private and public members.
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 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