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

168
Vistas
Difference between setinterval with an exist function and lambda expression for class in js

I'm making a simple game with javascript that you can fire bullet to enemies. Actually I don't have any problem making it but:

I made a class for my bullets that it has a Move function and I want to set an interval for it but when I set an interval in my constructor like this:

    setInterval(this.Move, 0);

I see this error:

uncaught TypeError: Cannot read properties of undefined (reading 'style') at Move (game.js:152)

But when I set and inverval like this:

    setInterval(() => {
        this.Move();
    }, 0);

It works without any problem.

I just what to know what is wrong with first one, I think the second way, you're making an extra thing (lambda expression).

Bullet Class: https://i.stack.imgur.com/q23Lk.png

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

0

It's a good question. The key difference is the use of the arrow function. Arrow functions are designed to bind to the scope that they are defined in.

By simply passing this.Move to setInterval, setInterval will invoke the function without binding to the class/instance scope.

The code below demonstrates several ways you could have passed this.Move to setInterval. Some have the correct scope, some don't, hopefully this will help your understanding.

let outside_function = undefined;

class X {

    constructor() {
        this.message = 'moving'

        // function is not bound to instance
        setInterval(this.move, 1000); // undefined

        // function is bound to instance
        setInterval(this.move.bind(this), 1000) // 'moving'

        // arrow function binds to 'this'
        setInterval(() => this.move(), 1000) // 'moving'

        // outside_function has no relationship with the class
        outside_function = this.move;
        setInterval(outside_function, 1000); // undefined
        setInterval(outside_function.bind(this), 1000) // 'moving'
    }

    move() {
        console.log(this.message)
    }
}

// also note that we can call the function like this
// again, no class instance here
X.prototype.move() // undefined

new X();
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