2017-08-01 44 views
2

财产“的className”我是新来的这一点,会很感激,如果有人可以解释:的Javascript滑块:遗漏的类型错误:无法设置的不确定

为什么我得到遗漏的类型错误:无法设置属性“的className '用下面的代码未定义?

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); 

}); 

当我这样做没有Slider()类它工作正常。

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'; 
} 
+0

的可能的复制[?如何访问正确的\'这\'回调内(https://stackoverflow.com/questions/20279484/how-to-access-the-correct-这回调内) –

+0

MDN是一个很好的资源,如果你想了解更多:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this – phuhgh

+0

伟大的联系这是我需要的,谢谢。 – HelloWorld

回答

3

看起来像setInterval创建它自己的上下文。尝试:

setInterval(this.nextSlide.bind(this), slideDuration); 
相关问题