Defining a recursive function in a Prototype class?

I am trying to create an image rotator class that cycles through an arbitrary number of images in an unordered list. Is it possible to define a recursive function in a class declaration? For instance:

var Rotator = Class.create() {
 initialize: function() {
  do something...

  this.rotate();
 }

 rotate: function() {
   do something...

   this.rotate()
 }
}

He is currently throwing the error message "this.rotate () is not a function"

+3
source share
2 answers

Answer:

, , ( , , ), . , , ( ) rotate, , , rotate.

, , this.rotate . ? - :

var r = new Rotator();
setInterval(r.rotate, 1000);

( rotate):

setInterval(this.rotate, 1000);

... , ( ) setInterval. :

var r = new Rotator();
setInterval(r.rotate.bind(r), 1000);

( rotate):

setInterval(this.rotate.bind(this), 1000);

Function # bind, , . Javascript .

:

var Rotator = Class.create() {
...
}

var Rotator = Class.create({
...
});

. , , :

var Rotator = Class.create({ // <= open brace *within* the parens

    initialize: function() {
        // do something...

        this.rotate();
    },                       // <= missing comma was here

    rotate: function() {
        // do something...

        this.rotate();
    }

    return pubs;
});                          // <= close the braces and parens here

( ):

FWIW, , , , (as , ) ( ). , ( , , - ):

var Rotator = Class.create((function(){
    var pubs = {};

    pubs.initialize = initialize;
    function initialize() {
        // do something...

        this.rotate();
    }

    pubs.rotate = rotate;
    function rotate() {
        // do something...

        this.rotate();
    }

    return pubs;
})());

( pubs function ) .

+5

, , , "this" . , . (.. function), IE. arguments.callee, , , arguments - , .

0

Source: https://habr.com/ru/post/1741796/


All Articles