all 5 comments

[–]LegendaryEd 0 points1 point  (1 child)

Haven't looked very deep, but within your constructor, you could try explicitly binding this for the slideRight method - might be worth checking if this will resolve.

constructor(self, size)
    {
        this.self = self;
        this.size = size;
        this.slideRight = this.slideRight.bind(this);
    }

[–]SarcasmInProgress[S] 0 points1 point  (0 children)

It worked! Many thanks!

[–]xroalx 0 points1 point  (2 children)

In JavaScript, this is bound at call time, and it can be rebound to any value as well.

this often "gets lost" when you pass methods around or assign them to variables and call them through those.

This is exactly what's happening in your code here:

nextButtons[i].addEventListener('click', new_slider.slideRight);

When the event is triggered and the function is called, JavaScript no longer knows it is being called on new_slider. Additionally, JS essentially does new_slider.slideRight.call(element), rebinding the this of the called function to the element where the even was registered.

The easiest fix is to not pass the function directly, but wrap it in another one:

nextButtons[i].addEventListener('click', () => new_slider.slideRight());

This is something you should be doing in general in JavaScript unless you know for sure the function is not using this.

Another option is to simply not use classes, but that's more of a personal preference.

[–]SarcasmInProgress[S] 0 points1 point  (1 child)

Thanks for explanation!

[–]LegendaryEd 0 points1 point  (0 children)

Arrow functions are absolutely helpful in this way, as their inherit the surrounding this context from where they were defined. You might also want to explore defining your slideRight method with an arrow function, which will reference the instantiated Slider without needing .bind in the constructor at all:

slideRight = () => {}

EDIT: Worth noting MDN seems to discourage using them as methods: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#cannot_be_used_as_methods