Skip to content

Instantly share code, notes, and snippets.

@ChuntaoLu
Last active January 4, 2016 00:59
Show Gist options
  • Save ChuntaoLu/8544917 to your computer and use it in GitHub Desktop.
Save ChuntaoLu/8544917 to your computer and use it in GitHub Desktop.
JavaScript module pattern: Function defines private variables and functions. Privileged functions can access private variables and functions via closure. The function returns the privileged functions or stores them in accessible place.
var serial_maker = function(){
// produce an object that produces unique strings.
var prefix = '';
var seq = 0;
return {
set_prefix: function (p) {
prefix = String(p);
},
set_seq: function(s) {
seq = s;
},
gen_serial: function () {
result = prefix + seq;
seq += 1;
return result;
}
};
};
var x = serial_maker();
x.set_prefix('abc');
x.set_seq(12345);
var serial_1 = x.gen_serial();
console.log(serial_1) // => 'abc12345'
// pass 'gen_serial' to 3rd party
var create_serial = x.gen_serial;
// 'create_serial' can still generate serial
var serial_2 = create_serial();
console.log(serial_2) // => 'abc12346'
// 'create_serial' can not set prefix or sequence
create_serial.set_prefix('fff'); // TypeError: object has no method 'set_prefix'
create_serial.set_seq(987654); // TypeError: object has no method 'set_seq'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment