When utilizing the method, it retrieves data from the object provided as state
:
const defaultObject = (state) => ({
posx: state.posx,
posy: state.posy,
firstx: () => {
return state.posx * CELLSIZE // <== Take note that you're reading from `state`
}
})
However, it is essential to read data from the newly created object instead of the original one. Yet, due to the complexity involved in copying elements without inheritance but through functions like Object.assign
, arrow functions cannot be used for the firstx
function. Instead, a standard function should be utilized while ensuring that this
points to the appropriate location when called:
const defaultObject = (state) => ({
posx: state.posx,
posy: state.posy,
firstx: function() {
return this.posx * CELLSIZE; // <== Observe the change in reference to `this`
}
})
For demonstration purposes, see the live example below:
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
The choice between using function notation or method notation for defining firstx
doesn't have much impact unless super
is employed within firstx
.
If your preference is for a getter, an alternative approach could involve creating a getter like so:
const defaultObject = (state) => ({
posx: state.posx,
posy: state.posy,
get firstx() {
return this.posx * CELLSIZE; // <== Notice the shift towards reading from `this`
}
})
However, when making use of Object.assign
, the value rather than the property descriptor linked to the getter is assigned to the new object. If needed, the property descriptor can be copied over after the assignment process as indicated by the '***' comments in the code snippet above.
In cases where flexibility in how wall
manipulates objects is preferred over direct augmentation, altering the approach recommended by Oriol in this solution might present a simpler solution.