Why is composition done with inner functions in JavaScrirpt?

Viewed 49

I have been reading about composition but every tutorial I see does something similar to the following.

const eater = (state) => ({
  eat(amount) {
    console.log(`${state.name} is eating.`)
    state.energy += amount
  }
});


function Dog(name, energy, breed) {
  let dog = {
    name,
    energy,
    breed,
  }

  return Object.assign(
    dog,
    eater(dog),
    sleeper(dog),
    player(dog),
    barker(dog),
  )
}

const leo = Dog('Leo', 10, 'Goldendoodle')
leo.eat(10) // Leo is eating
leo.bark() // Woof Woof!

Why do we need the Eater function to return the function we want to add as a property?

By extension, why do we need to send the object we want the method to be added to?

why not do something like the following?

const eat = (amount) => {
  console.log(`${this.name} is eating.`)
  this.energy += amount
}

function Dog(name, energy, breed) {
  let dog = {
    name,
    energy,
    breed,
  }

  return Object.assign(
    dog, {
      eat
    }, {
      sleep
    }, {
      play
    }, {
      bark
    }
  )
}

const leo = Dog('Leo', 10, 'Goldendoodle')
leo.eat(10) // Leo is eating
leo.bark() // Woof Woof!

0 Answers
Related