访问另一个原型函数的Javascript原型 [英] Javascript prototype accessing another prototype function

查看:46
本文介绍了访问另一个原型函数的Javascript原型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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");
});

这是我的 Scroller 代码,但是当我尝试运行它时,它给了我以下错误:Uncaught TypeError: this.slideTo is not a function"

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"

推荐答案

setInterval 调用一个函数时,它会使用 context(或 this value) 的 window (即它在全局范围/上下文中调用函数).您需要确保 nextSlide 中的上下文是正确的.

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.

试试:

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

这篇关于访问另一个原型函数的Javascript原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆