Jump to content

Javascript Object Problems


MrFish

Recommended Posts

I'm trying to make an animated gif class for the new html canvas. I start out by loading a bunch of images to the class and calling the start() function. This function does a setInterval function to call a run() function every second. But I can't get the function run to call any variables inside the class. They will all come up "undefined" or "NaN"

function AnimatedGif(){	//Variables	this.frames = new Array();	this.frameDuration = 1000;	this.image = new Image();	this.frame = 0;	this.runInterval;		this.loadImage = function(url)	{		fl = this.frames.length;		img = new Image();		img.src=url;		this.frames[fl] = img;	}		this.start = function()	{		this.runInterval = setInterval(this.run, this.frameDuration)	}		this.stop = function()	{		this.clearInterval(this.runInterval);		}		this.run = function()	{		frame = this.frame; //This is undefined at first, then NaN		frames = this.frames;		frameLength = frames.length;		this.image = frames[frame];		this.frame++;		if(this.frame == frameLength)		{			this.frame = 0;		}	}}

I've tried putting this.run in double quotes but then it won't even run.

Link to comment
Share on other sites

you should try declaring your local variable with the var keyword. did you try it as "this.run()"?it's most likely a scope issue with this and what it references within the setinterval function. you coudl trying something like this:

this.start = function(){  var ref = this;  this.runInterval = setInterval(ref.run, ref.frameDuration);};

Link to comment
Share on other sites

In order to specify the scope that the function runs in, one easy way is to add a createDelegate method to functions with this code:

Function.prototype.createDelegate = function(obj, args){  var method = this;  return function() {	var callArgs = args || arguments;	return method.apply(obj || window, callArgs);  };}

Then use this:this.runInterval = setInterval(this.run.createDelegate(this), this.frameDuration)That will make sure that when the function executes, this is set to the same object, or it's running in the same scope.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...