如何在高阶函数内部绑定函数引用?组成重于继承

时间:2019-07-28 21:00:26

标签: javascript

我正在尝试将每个函数引用绑定到特定的动物,但它从未引用我期望的正确的动物?

我曾尝试使用各种.call,.binds,但不确定如何滥用它们。

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()

我希望每个实例化的动物都引用自己的名字和能量。但这是不确定的。

1 个答案:

答案 0 :(得分:2)

这里没有理由使用bind。行为函数只需要以动物作为参数来调用,它们返回带有闭包的对象。使用

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