Michaël
Michaël

Reputation: 609

How to properly set a new value for a variable into a javascript class

I would like to check the value of a variable inside my requestAnimationFrame function. I implement this value on the scroll wheel event. It seems to work but when I check the value inside my RAF fonction, it's still set at its first value.

I wonder how can I properly set my this.deltaY value ? Thank you very much

class MyClass
{
    constructor ()
    {   
        this.deltaY = 0;
    }

    init ()
    {
        this.playRAF();
        window.addEventListener('wheel', function(e) {
            this.deltaY = e.deltaY;

            console.log(this.deltaY); 
            // it returns a number
        });

    }

    playRAF ()
    {
        this.leRaf = requestAnimationFrame(this.playRAF.bind(this));
        
        console.log(this.deltaY); 
        // it returns 0 all the time despite the function above :(
    }
}

//////

const foo = new MyClass();
foo.init();

Upvotes: 0

Views: 62

Answers (1)

Aobo Cheng
Aobo Cheng

Reputation: 4528

This is an this issue

pay attention to this block, in the event listener callback, this is window, instead of the class instance as you thougt it is.

window.addEventListener('wheel', function(e) {
  this.deltaY = e.deltaY;

  console.log(this.deltaY); 
  // it returns a number
});

try to check the value window.deltaY, you will find that it's your logged number, or try a breakpoint debugging, the this in the function(e){} is Window object.

turn it into

window.addEventListener('wheel',(e) => {
  this.deltaY = e.deltaY;

  console.log(this.deltaY); 
  // it returns a number
});

will solve this problem, as the arrow will not create a function block, this will be the class instance as expected.

Upvotes: 1

Related Questions