循环,计数和setInterval方法

时间:2010-02-03 02:42:06

标签: javascript function loops

1)这种构造技术是否有效?或者它需要有this.start()?

2)索引会在任何时候重置吗?

var imageRotate = new tRotate();
window.tRotate = function(){
__construct();

this.images = new Array();
this.index = 0;



this.__construct = function(){
  tRotate.start();
  // Do other things
}
this.start = function(){
    // yadadaa
    this.interval = setInterval("this.next()",500);
}
this.pause = function(){
    clearInterval(this.interval);
}
this.last = function(){
    --index;
}
this.next = function(){
    ++index;
}
}

1 个答案:

答案 0 :(得分:1)

1)函数表达式的排序与其他表达式一样。因此,您对__construct()new tRotate()的来电将失败。要么在最后调用它:

tRotate = function () {
    this.__construct = function () {/* ... */}
    /* ... */


    this.__construct();
}
imageRotate = new tRotate();

或使用函数声明而不是表达式:

imageRotate = new tRotate();
function tRotate () {
    __construct();

   function __construct() {/* ... */}

   /* ... */
}

2)如果手动重置,index可以重置:

imageRotate.index = 0;

只要您不触摸它,它就不会被重置。

更新:我刚才意识到,还有几点需要评论:

1)在javascript中,index未引用this.index。所以你需要将你的方法改为:

this.next = function () {
    this.index ++;
}

2)在javascript中,this不一定是指方法所属的对象。具体而言,对于setInterval执行的函数,this引用window对象。所以你需要在一个闭包中捕获this。有几种方法可以做到这一点:

function tRotate () {
    var self = this; // self refers to the correct 'this'

    this.start = function () {
        self.interval = setInterval(self.next,500);
             /* note: you need to pass a reference here, a string
              *       won't work because in the context of the
              *       window object the variable self is undefined
              */
    }

    /* ... */
}

function tRotate () {
    function makeStartMethod (self) {
        self.interval = setInterval(self.next,500);
    }
    this.start = makeStartMethod(this);

    /* ... */
}