Last active
April 14, 2020 23:42
-
-
Save Jiert/efa5a30200d1ebb62122 to your computer and use it in GitHub Desktop.
Composition using factory functions and Object.assign()
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 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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why factory functions that return objects and not just object literals?