Skip to content

Instantly share code, notes, and snippets.

@Jiert
Last active April 14, 2020 23:42
Show Gist options
  • Save Jiert/efa5a30200d1ebb62122 to your computer and use it in GitHub Desktop.
Save Jiert/efa5a30200d1ebb62122 to your computer and use it in GitHub Desktop.
Composition using factory functions and Object.assign()
var runner = function(){
return {
run: function(){
console.log(this.name + ' is running away!');
}
};
};
var swimmer = function(){
return {
swim: function(){
console.log(this.name + ' decided to have a dip in the pool');
}
};
};
// Compose an Athlete
var athlete = function(){
return Object.assign({}, runner(), swimmer() );
};
// Create a Runner
var goose = Object.assign({ name: 'Goose'}, runner() );
goose.run();
// Create a Runner and Swimmer
var jared = Object.assign({ name: 'Jared' }, runner(), swimmer() );
jared.run();
jared.swim();
// Or do the same thing but with an Athlete
var frog = Object.assign({name: 'Frog'}, athlete() );
frog.run();
frog.swim();
@astrotim
Copy link

astrotim commented Sep 7, 2016

Why factory functions that return objects and not just object literals?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment