So I'm brushing up on my vanilla Javascript, specifically for animation, and I came across a tutorial with the following code:
function sprite(options){
var spr = {},
frameIndex = 0,
tickCount = 0,
ticksPerFrame = options.ticksPerFrame || 0,
numberOfFrames = options.numberOfFrames || 1;
spr.context = options.context;
spr.width = options.width;
spr.height = options.height;
spr.image = options.image;
spr.loop = options.loop;
spr.render = function(){
console.log("render");
//console.log("height: ", spr.height);
//console.log("width: ", spr.width);
//console.log("context: ", spr.context);
//console.log("image: ", spr.image);
// Clear Canvas
spr.context.clearRect(0, 0, spr.width, spr.height);
// Draw animation
spr.context.drawImage(
spr.image,
frameIndex * spr.width / numberOfFrames,
0,
spr.width / numberOfFrames,
spr.height,
0,
0,
spr.width / numberOfFrames,
spr.height
);
};
spr.update = function(){
tickCount += 1;
if (tickCount > ticksPerFrame){
tickCount = 0;
if (frameIndex < numberOfFrames - 1){
frameIndex += 1;
} else if (spr.loop) {
frameIndex = 0;
}
}
};
return spr;
}
I understand all of the logic and everything, but how are
frameIndex
tickCount
ticksPerFrame
numberOfFrames
accessible from the render()
and update()
methods after spr
has been returned? As far as I can tell, they're local functions to the sprite
function and shouldn't be accessible after instantiation.