views:

51

answers:

1

1) Would this construct technique work? Or would it need to have this.start()?

2)Would the index reset at any point?

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  A: 

1) Function expressions are evaluated in order just like any other expressions. So your call to __construct() and new tRotate() will fail. Either call it at the end:

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


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

or use function declarations instead of expressions:

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

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

   /* ... */
}

2) The index can be reset if you manually reset it:

imageRotate.index = 0;

as long as you don't touch it, it won't be reset.

update: I just realised, several more things to comment on:

1) In javascript, index does not refer to this.index. So you need to change your methods to:

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

2) In javascript, this does not necessarily refer to the object the method belongs to. Specifically, for functions executed by setInterval, this refers to the window object. So you need to capture this in a closure. There are several ways to do 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
              */
    }

    /* ... */
}

or

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

    /* ... */
}
slebetman