this is a theoretical question about composable OOP in JS.
Suppose I want to reason around objects in terms of their behaviors, which one of the approaches below is best and why?
Approach #1:
var createHero = (fname, lname) => ({ firstName: fname, lastName: lname })
var canWalk = self => {
self.walk = () => (console.log('Walking...'), self)
}
var withUtilityBelt = self => {
var powers = []
self.addPower = power => (powers.push(power), self)
self.getPowers = () => powers.slice()
}
var combine = (self, behaviors) => {
behaviors.forEach(b => b(self))
}
var batman = createHero('Bruce', 'Wayne')
combine(batman, [canWalk, withUtilityBelt])
batman
.walk()
.addPower('money')
.addPower('technology')
.addPower('intelligence')
console.log(batman.getPowers())
Approach #2:
var createHero = (fname, lname) => ({ firstName: fname, lastName: lname })
var canWalk = self => {
return {
walk: () => (console.log('Walking...'), self)
}
}
var withUtilityBelt = self => {
var powers = []
return {
addPower: power => (powers.push(power), self),
getPowers: () => powers.slice()
}
}
var combine = (self, behaviors) => {
behaviors = behaviors.map(b => b(self))
return Object.assign(self, ...behaviors)
}
var batman = createHero('Bruce', 'Wayne')
combine(batman, [canWalk, withUtilityBelt])
batman
.walk()
.addPower('money')
.addPower('technology')
.addPower('intelligence')
console.log(batman.getPowers())
I have the sensation that the latter is better than the former as behaviors are objects themselves, yet I don't know if there's any practical advantage in it.
What do you think? Am I missing something useful from a composition point of view??
Thanks in advance! :D
Aucun commentaire:
Enregistrer un commentaire