Javascript 如何在高阶函数内部绑定函数引用?组合重于继承
我试图将每个函数引用绑定到一个特定的动物,但它从来没有引用我期望的正确的动物 我尝试过使用各种.call、.binds,但我不确定我是如何滥用它们的Javascript 如何在高阶函数内部绑定函数引用?组合重于继承,javascript,Javascript,我试图将每个函数引用绑定到一个特定的动物,但它从来没有引用我期望的正确的动物 我尝试过使用各种.call、.binds,但我不确定我是如何滥用它们的 const sleeper = animal => ({ sleep() { animal.energy += 10; console.log(`${animal.name} is sleeping! Energy is now ${animal.energy}!`); } }); const eater = ani
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()
我希望每个实例化的动物都有一个自己名字和能量的引用。但是它是未定义的。这里没有理由使用
bind
。行为函数只需要将动物作为参数调用,它们返回一个带有闭包的对象。使用
const boundFunctions = args.map(func => func(animal))
我不认为这可以被称为“组合重于继承”,因为您并没有真正将行为用作组件。顺便说一句,如果你不使用以特定的
动物为参数的函数,我认为这会变得简单得多。只需编写使用this
关键字的方法,该关键字是后期绑定的(在调用站点),因此您所需要做的就是将该方法放在动物对象上。有趣的是,我阅读了有关合成的内容,这意味着将它们更改为它们所做的事情的反映,而不是它们是什么。例如,一只老虎是“x和y”,另一只动物是“x、y、z和更多”。这是我第一次想到实现它。我得多读一些关于这个模式的书。太棒了。我知道我很接近,但我很确定我必须绑定函数引用。谢谢你把我从窗台上说服了。