Skip to content

Instantly share code, notes, and snippets.

@paulhhowells
Last active December 16, 2015 12:39
Show Gist options
  • Save paulhhowells/5436322 to your computer and use it in GitHub Desktop.
Save paulhhowells/5436322 to your computer and use it in GitHub Desktop.
Douglas Crockford’s Module pattern, but it starts (and finishes) as an object rather than a function. A publicly accessible object metamorphoses into an object with public methods and variables, and private methods and variables.
metamorphosis = {
defaults : {
thing : 4
},
init : function (options) {
var
the = this,
o, // private object
p; // public object
o = {
hidden : 'a private variable'
};
p = {
v : 64,
show : function () {
console.log('get: defaults.thing: ' + the.defaults.thing);
console.log('get: private var: ' + o.hidden);
},
get : function () {
return o.hidden;
},
set : function (arg) {
o.hidden = arg;
},
make : function () {
var r = {};
return r;
}
};
metamorphosis = p;
}
};
metamorphosis.init(); // one could pass in an argument and extend or modify defaults
metamorphosis.show(); // defaults.thing and o.hidden still exist, but as private variables
console.log(metamorphosis.v); // 64
console.log(metamorphosis.defaults.thing); // will fail, as defaults are now private
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment