Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

166
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!