Created
August 11, 2011 11:37
-
-
Save sgentile/1139448 to your computer and use it in GitHub Desktop.
Javascript Module Pattern
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
<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