我看了关于合成的教程,它使您可以像这样合成对象:
const eater = (state) => ({
eat(amount) {
console.log(state.name + ' is eating');
state.energy += amount;
}
});
// using a factory
const Dog = (name, energy, breed) => {
let dog = {
name,
energy,
breed
};
return Object.assign(dog, eater(dog));
};
const leo = Dog('Leo', 10, 'Pug');
leo.eat(10); // Leo is eating
console.log(leo.energy); // 20
我想知道您是否可以做类似的事情,以及这样做是否有不利之处:
const eater = {
eat(amount) {
console.log(this.name + ' is eating');
this.energy += amount;
}
};
const Dog = (name, energy, breed) => {
let dog = {
name,
energy,
breed,
...eater
};
return dog;
};
const leo = Dog('Leo', 10, 'Pug');
leo.eat(10); // Leo is eating
console.log(leo.energy); // 20
如您所见,我没有使用Object.assign
创建函数并将其分配给该对象,而是使用一种方法创建了另一个eater
对象,然后将该eater
对象展开并将其添加到dog
在工厂内部创建对象。
所以,这样做有什么问题吗?
谢谢!
这两种方法非常相似。两者都是可行且好方法。
这里是区别:
第一种方法:eater
是工厂功能
eat
对象和dog
功能eat
方法已绑定:let leoEat = leo.eat;
leoEat(10); //works
eater
是一个对象eater
对象和eat
函数被重用eat
未绑定:const leo = Dog('Leo', 10, 'Pug');
const animal = {name: 'Animal', energy: 0};
leo.eat.call(animal, 30); // Animal is eating
console.log(animal.energy); // 30
console.log(leo.energy); // 10
Eater
和Dog
是类eat
函数被重用eat
未绑定class Eater {
eat(amount) {
console.log(this.name + ' is eating');
this.energy += amount;
}
};
class Dog extends Eater{
constructor (name, energy, breed) {
super();
Object.assign(this, {
name,
energy,
breed
})
}
};
const leo = new Dog('Leo', 10, 'Pug');
leo.eat(10); // Leo is eating
console.log(leo.energy); // 20
console.log(leo instanceof Dog) //true
console.log(leo instanceof Eater) //true