Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

204
Vistas
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:

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.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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);

about 4 years ago · Juan Pablo Isaza Denunciar

0

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);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda