简体   繁体   中英

How to bind function references inside of a higher order function? Composition over inheritance

I'm trying to create bind each function reference to a specific animal but it's never referring to the right animal I expect?

I have tried using various .call, .binds, but I am unsure how I'm misusing them.

const sleeper = animal => ({
  sleep() {
    animal.energy += 10;
    console.log(`${animal.name} is sleeping! Energy is now ${animal.energy}!`);
  }
});

const eater = animal => ({
  eat() {
    animal.energy += 5;
    console.log(`${animal.name} is eating! Energy is now ${animal.energy}!`);
  }
});

const speaker = animal => ({
  speak() {
    animal.energy -= 3;
    console.log(`${animal.name} has uttered something!`)
  }
})


const Animal = (...args) => {

  return (name, energy = 0) => {
    const animal = {
      name,
      energy,
    }

    // this is where I am confused
    const boundFunctions = args.map(func => {
      return func.bind(animal)()
    })


    return Object.assign(animal, ...boundFunctions)
  }
}

const Monkey = Animal(sleeper, eater)
const Tiger = Animal(sleeper, eater, speaker)

const Reggie = Monkey("Reggie");
const Tony = Tiger('Tony')

Reggie.sleep()
Tony.eat()

I'd like each instantiated animal to have a reference to their own name and energy. But it is undefined.

There's no reason to use bind here. The behavioural functions just need to be called with the animal as an argument, they return an object with a closure. Use

const boundFunctions = args.map(func => func(animal))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM