I’m 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 within a class declaration? E.g:
var Rotator = Class.create() {
initialize: function() {
do something...
this.rotate();
}
rotate: function() {
do something...
this.rotate()
}
}
It currently throws an error stating “this.rotate() is not a function”
Answer:
What you have there should work (except for a couple of what I think are typos; below), because you’re accessing the function from the property. Note that that means you’ll re-enter the top-most (most sub-classed)
rotatefunction if you’re using inheritance, because that’s the one that’s assigned to the instancerotateproperty.You said that it’s saying that
this.rotateis not a function. How are you calling it? Because if you’re doing something like this:or (within
rotate):…that’s not going to work, because you’re just passing the function (not its context) to
setInterval. This would work:or (within
rotate):That uses Function#bind to create a function that will set the correct context. More about functions vs. methods in Javascript in this post.
Typos:
should be
You also need a comma between the two functions in the object literal notation you’re using. So with those cleaned up it’s:
Named functions (and typo-avoidance, and private functions):
FWIW, you can avoid typos like leaving out the comma between functions and also get all the benefits of your functions having real names (as opposed to being anonymous functions bound to properties) plus getting private class-wide functions (if that’s useful to you). This is the idiom I mostly use (although I use a helper to make the syntax a small bit cleaner; the below is raw Prototype):
More on that idiom (and why you can’t combine the
pubsandfunctionlinks above) in the linked post.