1

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.

dartanian300
  • 247
  • 2
  • 16

1 Answers1

2

They are local to the sprite function.

The other functions you mention are defined inside the sprite function and so have access to any variables that are in its scope.

They continue to be available after the sprite function has finished because they have been returned. This is called a closure.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • So if you instantiate other objects, do they all draw from the same variables or will they have their own copies just as if they had been defined as `spr.varname`? – dartanian300 Feb 11 '16 at 14:20