简体   繁体   中英

JavaScript – Call a function of the prototype from another prototype function?

I am trying to write a simple slider using plain JavaScript. As these are my first steps using the prototype of an object & following an object oriented approach in general, I am quite confused sometimes, so please bear with me.

Here is what I have:

function MySlider(noOfSlides, startSlide){
    this.noOfSlides = noOfSlides;
    this.startSlide = startSlide;
    this.currentSlide = this.startSlide;
}

MySlider.prototype.nextSlide = function(){
    this.currentSlide++;
    console.log(this.currentSlide);
    return this.currentSlide;
};

MySlider.prototype.startSlider = function(){
    setInterval(function(){
        MySlider.nextSlide();
    }, 2000);
};

var slides = new MySlider(4, 1);

document.getElementById("button").addEventListener("click", function(){
    slides.startSlider();
}, false);

Unfortunately, this isn't working, after the 2 seconds wait because of setInterval , I get the following error: TypeError: MySlider.nextSlide is not a function .

While I understand what the problem is, I don't know what to change. I already tried it with this.nextSlide() but that didn't work either. My guess is that it has something to do with the prototype chain, but I am still trying to understand this.

How to solve this problem? Or is it a bad idea in general to it this way?

You need to preserve the context (the value of this ) when you set up the timer handler:

MySlider.prototype.startSlider = function(){
    var slider = this;
    setInterval(function(){
        slider.nextSlide();
    }, 2000);
};

By saving the value of this , you ensure that when the interval timer goes off it'll be able to invoke the "nextSlide" function in the context of the correct object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM