I've been seeing examples of factory functions like this,
const dog = () => {
const sound = 'woof'
return {
makeSound: () => console.log( sound )
}
}
const poodle = dog()
poodle.makeSound() // woof
But this way, every dog created will have an extra makeSound function created in memory. Wouldn't it be much better if the functions are external to the object created and just have the object be passed to the sound function like so?
const dog = () => {
return {
sound: 'woof'
}
}
const makeSound = obj => console.log( obj.sound )
const poodle = dog()
makeSound( poodle ) // woof
What's the advantage of having the functions within each object created by the factory function vs having it outside and passing in the object you want to run the function with to it?