1

So I have a class declaration and in my constructor I want to add an event listener when the window scrolls. Something like this:

class MyClass {
    constructor(el, options) {
        // (...) initiating this properties and methods
        $window.on('scroll', this.onScroll);
    }

When I add my event listener I lose the this scope (onScroll() creates its own this instance), but if I use $window.on('scroll', () => this.scroll()); I keep my this scope. Is there a way to keep my scope and not using the arrow function?

Comum
  • 453
  • 5
  • 21

2 Answers2

3

You can use Function#bind. It returns the function attached to the given context.

class MyClass {
    constructor(el, options) {
        $window.on('scroll', this.onScroll.bind(this));
    }
}
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
2

Do it like below:

class MyClass {
    constructor(el, options) {        
        $window.on('scroll', this.onScroll.bind(this));
    }
}

Or just modify the way you define onScroll function:

this.onScroll = () => { ... }
Faly
  • 13,291
  • 2
  • 19
  • 37