2016-01-21 35 views
0

我想對於一個練習,創建沒有jQuery的幻燈片。我試圖在Javascript中學習OO。OO的JavaScript幻燈片沒有jQuery的不能找出錯誤

'use strict'; 

var Slideshow = (function() { 

function Slideshow(element, options) { 
    options = options || {}; 
    this.slideshow = document.querySelector(element || '.slideshow'); 
    this.slides = this.slideshow.children; 
    this.slideSpeed = options.slideSpeed || 3000; 
    this.autoPlay = options.autoPlay || true; 
    this.pauseOnHover = options.pauseOnHover || true; 
    this.autoPlayTimer = null; 
    this.pause = false; 
    this.currentSlide = -1; 

    if (this.autoPlay) { 
     this.play(); 
    } 
} 

Slideshow.prototype.slideIterator = function() { 
    this.currentSlide = (this.currentSlide + 1) % this.slides.length; 
}; 

Slideshow.prototype.play = function() { 
    if (this.autoPlayTimer) { 
     clearInterval(this.autoPlayTimer); 
    } 

    if (this.slides.length > 0 && this.pause !== true) { 
     this.autoPlayTimer = setInterval(this.slideIterator.bind(this), this.slideSpeed); 
    } 
}; 

Slideshow.prototype.playTimerClear = function() { 
    if (this.autoPlayTimer) { 
     clearInterval(this.autoPlayTimer) 
    } 
}; 

Slideshow.prototype.pause = function() { 
    this.playTimerClear(); 
    this.pause = true; 
}; 

return Slideshow 

})(); 

有一個錯誤:未捕獲的類型錯誤:在22行

我想這是因爲這種變化不能讀取未定義的屬性「長度」,這是不是出於某種原因不再幻燈片...

+0

請發表你的問題你的代碼,而不是僅僅將它鏈接 – Bergi

回答

0

問題是,改變的setInterval範圍,使this將窗口。你可以通過綁定來修復它。

this.autoPlayTimer = setInterval(this.slideIterator, this.slideSpeed); 

this.autoPlayTimer = setInterval(this.slideIterator.bind(this), this.slideSpeed); 

MDN bind()