Skip to content

Instantly share code, notes, and snippets.

@konijn
Created August 19, 2014 18:52
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 konijn/5a9ef2c4b002b6135a55 to your computer and use it in GitHub Desktop.
Save konijn/5a9ef2c4b002b6135a55 to your computer and use it in GitHub Desktop.
Compose
function merge(object, boltOn) {
//Simply merge the properties of boltOn into object
for(var property in boltOn)
if(boltOn.hasOwnProperty(property))
object[property] = boltOn[property];
return object;
}
function compose( /*Constructor1, Constructor2, ..*/ ) {
//Keep a closure reference for later
var constructorReferences = arguments;
return function ComposedConstructor() {
//Clone the constructors, we will modify the clones
var constructorClones = Array.prototype.slice.call(constructorReferences).map(function(Constructor) {
return new Object(Constructor);
});
var constructor = constructorClones.pop();
//Set up the prototype chain, without loosing the original prototypes thru `merge`
while(constructorClones.length) {
var nextConstructor = constructorClones.pop();
nextConstructor.prototype = merge(new constructor(arguments), nextConstructor.prototype);
constructor = nextConstructor;
}
//Call the first constructor with the arguments provided to the constructor
constructor = constructor.bind.apply(constructor, [null].concat(Array.prototype.slice.call(arguments)));
return new constructor();
};
}
function A(name) {
this.a = name;
console.log(arguments);
}
A.prototype.sayA = function() {};
function B() {
this.b = 2;
console.log(arguments);
}
B.prototype.sayB = function() {};
function C() {
this.c = 3;
console.log(arguments);
}
C.prototype.sayC = function() {};
var O = compose(A, B, C);
var o = new O('Samsung');
// {[object Object] { a: "Samsung",b: 2,c: 3,sayA: function,sayB: function,sayC: function}
console.log(o);
console.log(o instanceof A); //true
console.log(o instanceof B); //true
console.log(o instanceof C); //true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment