Skip to content

Instantly share code, notes, and snippets.

@alexeyraspopov
Last active August 29, 2015 14:03
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 alexeyraspopov/89de609eb6fd6f84f263 to your computer and use it in GitHub Desktop.
Save alexeyraspopov/89de609eb6fd6f84f263 to your computer and use it in GitHub Desktop.
Traits in JavaScript with CommonJS Modules
var rolesComposition = require('./trait');
function Duck(swimMessage, flyMessage){
this.swimMessage = swimMessage;
this.flyMessage = flyMessage;
}
Duck.prototype = rolesComposition(require('./swimming'), require('./flying'));
function Penguin(swimMessage){
this.swimMessage = swimMessage;
}
Penguin.prototype = rolesComposition(require('./swimming'));
exports.flyMessage = 'default fly message';
exports.fly = function(){
console.log(this.flyMessage);
};
exports.swim = function(){
console.log(this.swimMessage);
};
function mixin(target, source){
Object.keys(source).forEach(function(key){
target[key] = source[key];
});
return target;
}
function array(object){
return Array.from ? Array.from(object) : Array.prototype.slice.call(object);
}
function rolesComposition(){
return array(arguments).reduce(mixin, {});
}
module.exports = rolesComposition;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment