Created
January 2, 2015 17:06
-
-
Save greenboxal/ed92781973a1ecb6f486 to your computer and use it in GitHub Desktop.
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
var util = require('util'); | |
exports.compose = function(object, trait) { | |
var dynamicConstructor = function(args) { | |
return object.apply(this, args); | |
}; | |
dynamicConstructor.prototype = object.prototype; | |
var constructor = function() { | |
this._child = new dynamicConstructor(arguments); | |
trait.apply(this, arguments); | |
}; | |
for (var key in object.prototype) { | |
var value = object.prototype[key]; | |
if (typeof value == 'function') { | |
constructor.prototype[key] = function() { | |
// Get the instance value in case something monkey patched it | |
return this._child[key].apply(this._child, arguments); | |
}; | |
} else { | |
Object.defineProperty(constructor.prototype, key, { | |
configurable: true, | |
enumerable: true, | |
writable: true, | |
get: function() { | |
return this._child[key]; | |
}, | |
set: function(value) { | |
this._child[key] = value; | |
} | |
}); | |
} | |
} | |
for (var key in trait.prototype) { | |
var descriptor = Object.getOwnPropertyDescriptor(trait.prototype, key); | |
if (descriptor) { | |
Object.defineProperty(constructor.prototype, key, descriptor); | |
} else { | |
constructor.prototype = trait.prototype[key]; | |
} | |
} | |
return constructor; | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment