Skip to content

Instantly share code, notes, and snippets.

@jabney
Last active August 29, 2015 14:19
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 jabney/41d983563675c891af00 to your computer and use it in GitHub Desktop.
Save jabney/41d983563675c891af00 to your computer and use it in GitHub Desktop.
Javascript augmentation pattern for a factory method
// This augmentation style is appropriate for a factory-style function,
// which might be something that was imported as part of a library.
var factory = function factory() {
var data = [];
// Return an object with one or more methods.
return {
init: function() {
data.push.apply(data, arguments);
return this;
},
items: function() {
return data.slice(0, data.length);
}
};
};
// This pattern augments the factory function, such that whenever
// the factory function is called, it has the augmented method(s).
factory = (function(obj) {
return function() {
var o = obj();
o.toString = function() {
return this.items().toString();
};
return o;
};
})(factory);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment