Object compostion 2

Home   »   Object compostion 2

const canCast = (state) => ({
  cast(spell) {
    console.log(`${state.name} casts ${spell}`)
    state.mana--
    console.log(state.mana)
  },
})

const canOtherThing = (state) => ({
  doOtherThing() {
    console.log('I am doing other stuff')
    console.log('and this is state that I access', state)
  },
})

const canFight = (state) => ({
  fight() {
    console.log(`${state.name} slashes at the foe`)
    state.stamina--
    const otherThing = canOtherThing(state)
    otherThing.doOtherThing()
  },
})

const createFighter = (name) => {
  const state = {
    name,
    health: 100,
    stamina: 100,
  }

  return Object.assign(state, canFight(state))
}

const fighter = createFighter('Slasher')
fighter.fight()

// Output
// Slasher slashes at the foe
// I am doing other stuff
// and this is state that I access { name: 'Slasher', health: 100, stamina: 99, fight: [Function: fight] }

Leave a Reply

Your email address will not be published. Required fields are marked *