2

I'm new to this, and would really appreciate if someone could explain:

Why do i get Uncaught TypeError: Cannot set property 'className' of undefined with the below code ?

require(
["jquery"],
function($) {

    function Slider() {

        this.slides = document.querySelectorAll('#slides .slide');          
        this.currentSlide  = 0;
        this.slideInterval = 0;

    }

    Slider.prototype.startSlider = function( slideDuration ) {
        this.slideInterval = setInterval( this.nextSlide, slideDuration );
    };

    Slider.prototype.nextSlide = function() {

        this.slides[ this.currentSlide ].className = 'slide';
        this.currentSlide = ( this.currentSlide+1 ) % this.slides.length;
        this.slides[ this.currentSlide ].className = 'slide showing';           

    };

    Slider.prototype.goToThis = function() {

    };

    Slider.prototype.goToNext = function() {

    };

    Slider.prototype.goToPrev = function() {

    };

    var slider = new Slider();
    slider.startSlider( 1000 );

});

When i do it without the Slider() class it works fine.

var slides = document.querySelectorAll('#slides .slide');
var currentSlide = 0;
var slideInterval = setInterval(nextSlide,2000);

function nextSlide() {
    slides[currentSlide].className = 'slide';
    currentSlide = (currentSlide+1)%slides.length;
    slides[currentSlide].className = 'slide showing';
}
HelloWorld
  • 193
  • 4
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Heretic Monkey Aug 01 '17 at 18:17
  • MDN is a great resource if you're interested in finding out more: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this – phuhgh Aug 01 '17 at 18:18
  • Great link this is what i needed, thanks. – HelloWorld Aug 01 '17 at 18:20

1 Answers1

3

It looks like setInterval create it's own context. try:

setInterval( this.nextSlide.bind(this), slideDuration );
qiAlex
  • 4,290
  • 2
  • 19
  • 35