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?
this, I recommend to read the MDN documentationthatandselfare great as it helps to understand scripts written by others.