简体   繁体   中英

Javascript prototype accessing another prototype function

function Scroller(id){
    this.ID = id;
    this.obj = $("#"+id);
    this.currentSlide = 1;

    var self = this;
    setInterval(self.nextSlide, 1000);
}

Scroller.prototype.nextSlide = function(){
    this.slideTo(this.currentSlide+1);
}

Scroller.prototype.slideTo = function(slide){
    // slide = (slide+this.obj.children().size()-1) % this.obj.children().size()+1; 
    // $("#"+this.ID+" > *:first-child").stop().animate({"margin-left": "-"+this.obj.get(0).offsetWidth*(slide-1)}, 1000);
    // currentSlide = slide;
}

$(document).ready(function(){
    new Scroller("actielist");
});

So this is my code for my Scroller, but when I try to run it, it gives me the following error: "Uncaught TypeError: this.slideTo is not a function"

When setInterval calls a function, it calls it with the context (or this value) of window (ie. it calls the function in the global scope/context). You need to make sure the context inside nextSlide is correct.

Try:

setInterval(self.nextSlide.bind(self), 1000);

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