Last active
August 29, 2015 14:19
-
-
Save jabney/41d983563675c891af00 to your computer and use it in GitHub Desktop.
Javascript augmentation pattern for a factory method
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
// 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