Wrox Home  
Search P2P Archive for: Go

  Return to Index  

javascript thread: invoking object methods within a timeout


Message #1 by =?iso-8859-1?Q?Hans_J=F6rg_Friedrich?= <hans.friedrich@b...> on Mon, 27 Aug 2001 11:54:52 +0200
I believe that when you come across this unfortunate situation,
you need to create a global variable that points to the object, and
then alert the object's property...

E.g. var oObjectOne =3D new theObject();
setInterval("alert(oObjectOne.a)", 1000);


/Robert




-----Original Message-----
From: Hans J=F6rg Friedrich [mailto:hans.friedrich@b...]
Sent: den 27 augusti 2001 11:55
To: javascript
Subject: [javascript] invoking object methods within a timeout


Hello,

I want to use a timeout (an interval exactly speaking) within a member
function of an object. The the code to be executed (the first parameter
of the setInterval function) is an invokation of another method of the
same object.

My problem is, when the method is called from the timer, 'this' points
to the window, not to the object like it should.

// just an example


function theObject()
{
	this.a =3D 100
	this.b =3D 2;
}

function addValues() // just to have a function to call
{
	alert("in addValues!\n" +
		  "this.a:\t" + this.a +
		  "\nthis.document.URL:\t" + this.document.URL );
	clearInterval(Timer); // comment this line if you don't see the
second alert
}

function addPerSecond()
{
	try{
		right =3D this.a;
		wrong =3D this.document.URL;
	}catch(e){
		alert("in addPerSecond!\n" + e.message);
	};
	Timer =3D window.setInterval("this.addValues()", 1000);
}

var anObject =3D new theObject();
var Timer;

theObject.prototype.addValues =3D addValues;
theObject.prototype.addPerSecond =3D addPerSecond;

anObject.addPerSecond();


Would be great if anyone could help.

Hans

  Return to Index