Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to call a function in an object that references itself?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading