Skip to content

Instantly share code, notes, and snippets.

@jabney
Last active August 29, 2015 14:22
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/b95cfc7696bf2dea2d3e to your computer and use it in GitHub Desktop.
Save jabney/b95cfc7696bf2dea2d3e to your computer and use it in GitHub Desktop.
JavaScript Factory Inheritance
(function() {
'use strict';
// Create a factory function (a function that returns an object).
function aFactory() {
// Create a data store.
var _data = [];
// Add supplied arguments to the data store.
if (arguments.length)
_data.push.apply(_data, arguments);
return {
// Store a reference to the factory that created this object.
factory: aFactory,
// Create a method to add items to the data store.
add: function add() {
_data.push.apply(_data, arguments);
},
// Create a method to iterate the data store.
each: function each(action, context) {
_data.forEach(action, context);
},
// Create a method to return a copy of this object.
copy: function copy() {
return this.factory.apply(null, _data);
},
// Create a method to clear the data.
clear: function clear() {
_data = [];
},
// Create a method to return a copy of the data object.
data: function data() {
return _data.slice(0, _data.length);
}
};
}
// Create a new factory function that will inherit from aFactory.
function myFactory() {
// Create a reference to the original factory.
var _super = aFactory.apply(null, arguments);
// Create a new object with the original factory as its prototype.
var self = Object.create(_super);
// Set the factory property of the new object.
self.factory = myFactory;
// Optionally provide a reference to the original factory.
self._super = _super;
// Add a new method to the new object.
self.toString = function toString() {
return this.data().join(',');
};
// Return the new object.
return self;
}
console.log('Create a factory with some starter data')
var f = myFactory(1, 2, 3);
console.log('Data:', f.data());
console.log('Add some items (4, 5, 6)');
f.add(4, 5, 6);
console.log('New data:', f.data());
console.log('Iterate the data store');
f.each(function(item) {
console.log(' item', item);
});
console.log('Factory method:', f.factory);
console.log('Super\'s factory method:', f._super.factory);
console.log('Output from toString:', '' + f);
console.log('Copy myFactory');
var nf = f.copy();
console.log('The copy\'s factory method:', nf.factory);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment