Skip to content

Instantly share code, notes, and snippets.

@sgentile
Created August 11, 2011 11:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgentile/1139448 to your computer and use it in GitHub Desktop.
Save sgentile/1139448 to your computer and use it in GitHub Desktop.
Javascript Module Pattern
<script type="text/javascript">
//from book 'Javascript the Good parts' p.58
//The methods do not make use of this or that.
//As a result, there is no way to com- promise the seqer.
//It isn’t possible to get or change the prefix or seq
//except as per- mitted by the methods. The seqer object
//is mutable, so the methods could be replaced, but
//that still does not give access to its secrets.
//seqer is simply a collection of functions, and
//those functions are capabilities that grant specific
//powers to use or modify the secret state.
var serial_maker = function(){
var prefix = '';
var seq = 0;
return {
set_prefix: function (p) {
prefix = String(p);
},
set_seq: function (s) {
seq = s;
},
gensym: function () {
var result = prefix + seq;
seq += 1;
return result;
}
};
};
var seqer = serial_maker();
seqer.set_prefix('Q');
seqer.set_seq(1000);
var unique = seqer.gensym();
console.log(unique);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment