该方法正在读取您作为state 传入的对象:
const defaultObject = (state) => ({
posx: state.posx,
posy: state.posy,
firstx: () => {
return state.posx * CELLSIZE // <== Note you're reading from `state`
}
})
相反,您想从您创建的对象中读取;但它比这更复杂,因为虽然您没有使用继承,但您正在复制一些东西,包括将该函数从一个对象复制到另一个对象(通过Object.assign)。因为您正在这样做,所以您不能为 firstx 函数使用箭头函数;您必须使用普通函数并依赖 this 在调用时正确设置:
const defaultObject = (state) => ({
posx: state.posx,
posy: state.posy,
firstx: function() {
return this.posx * CELLSIZE; // <== Note reading from `this`
}
})
现场示例:
const CELLSIZE = 16;
const defaultObject = (state) => ({
posx: state.posx,
posy: state.posy,
firstx: function() {
return this.posx * CELLSIZE; // <== Note reading from `this`
}
})
const wall = (posx, posy) => {
let setup = {
//Later there will be some not-inherited variables
}
let state = {
posx,
posy,
}
return Object.assign(
{},
defaultObject(state),
setup
)
}
const x1 = wall(2, 5)
console.log(x1.firstx()) // Returns 32
x1.posx = 1
console.log(x1.firstx()) // Returns 16
您可以使用函数表示法(如上)或方法表示法来定义firstx:
const defaultObject = (state) => ({
posx: state.posx,
posy: state.posy,
firstx() {
return this.posx * CELLSIZE; // <== Note reading from `this`
}
})
在这种情况下你使用哪个并不重要,因为你没有在firstx 中使用super。
你说你想要一个吸气剂;如果你愿意,你可以为它定义一个吸气剂:
const defaultObject = (state) => ({
posx: state.posx,
posy: state.posy,
get firstx() {
return this.posx * CELLSIZE; // <== Note reading from `this`
}
})
但是,当您使用Object.assign 时,它将读取该属性的值 并将其分配给新对象,而不是定义getter 的属性描述符.如果您愿意,您可以稍后将该属性描述符复制到自己身上,请参阅*** cmets:
现场示例:
const CELLSIZE = 16;
const defaultObject = (state) => ({
posx: state.posx,
posy: state.posy,
get firstx() { // ***
return this.posx * CELLSIZE; // ***
} // ***
})
const wall = (posx, posy) => {
let setup = {
//Later there will be some not-inherited variables
}
let state = {
posx,
posy,
}
const original = defaultObject(state); // ***
const obj = Object.assign({},
original, // ***
setup
)
Object.defineProperty( // ***
obj, // ***
"firstx", // ***
Object.getOwnPropertyDescriptor(original, "firstx") // ***
); // ***
return obj; // ***
}
const x1 = wall(2, 5)
console.log(x1.firstx) // Returns 32
x1.posx = 1
console.log(x1.firstx) // Returns 16
但是,如果您不同意让wall 复制对象而不是扩充它,那么Oriol's approach 更改wall 的工作方式要简单得多。