gpt4 book ai didi

javascript - 如何在高阶函数中绑定(bind)函数引用?组合优于继承

转载 作者:行者123 更新时间:2023-11-30 13:56:16 24 4
gpt4 key购买 nike

我正在尝试创建将每个函数引用绑定(bind)到特定动物,但它从来没有指代我期望的正确动物?

我尝试过使用各种 .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()

我希望每个实例化的动物都能引用它们自己的名字和能量。但它是未定义的。

最佳答案

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

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

关于javascript - 如何在高阶函数中绑定(bind)函数引用?组合优于继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57244928/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com