我试图建立一个对象,当我创建该对象的实例时,id喜欢将EventListener添加到特定对象。但这让我异常

Uncaught TypeError: Object #<HTMLDivElement> has no method 'nextSlide'


我有以下代码

//Constructor function
function CinnamonSlider (sliderID) {
// Settings - must be set.
    this.sliderID = sliderID;

    var nextController = document.querySelector('.'+this.sliderID+'-next');

    nextController.addEventListener("click", function(e) {
        this.nextSlide();
        e.preventDefault();
    });

}

CinnamonSlider.prototype.nextSlide = function() {
    console.log('next');
};

var mySlider = new CinnamonSlider('my-slider');


我在这里做错了什么?

谢谢!

最佳答案

事件处理程序中的this是元素,而不是类。将this的值存储在变量中

function CinnamonSlider (sliderID) {

    this.sliderID = sliderID;

    var nextController = document.querySelector('.'+this.sliderID+'-next');

    var self = this;

    nextController.addEventListener("click", function(e) {
        self.nextSlide();
        e.preventDefault();
    });

}

CinnamonSlider.prototype.nextSlide = function() {
    console.log('next');
};

var mySlider = new CinnamonSlider('my-slider');

09-20 08:45