I have an object that looks something like this:
const state = []
const spells = [
{
name: 'test',
channelDuration: 1000,
castDuration: 1000,
cast: () => {
state.push(THIS) // <--
}
}, {...}, {...}
]
When a player uses a spell, that spell gets stored into the game state and then waits for the channelDuration
and castDuration
to pass.
Once able to cast, it looks into the state and calls the cast
method:
State.quest.bossFightState[USER].spell.cast()
state = [Spell]
On said cast, i need to push the spell into the a new array called statuses
. However, i can't reference the object within the cast method without using some additional helper functions to grab the specific spell. And I dont want to pass add a parameter spell
into the cast method because that just seems dumb.
Any ideas? Or is a helper method the way to go here.
CodePudding user response:
I'm surprised nobody else caught this... You're using this
inside of an arrow function. The this
keyword acts differently in arrow functions - read more about that here
const state = [];
const spells = [
{
name: 'test',
cast: function () {
state.push(this);
},
},
];
spells[0].cast();
console.log(state);
CodePudding user response:
One option would be to use a function
or method instead of an arrow function, so that .cast
will have a this
referring to the outer object.
const state = []
const spells = [
{
name: 'test',
cast() {
state.push(this)
}
}
]
spells[0].cast();
console.log(state);