...

View Full Version : Recursion.



rlemon
07-27-2006, 05:02 PM
ok so apperently i don't know how to do this and i've searched google (for like 20 minutes) and can't find anything. i've probably passed over it and not realized. :confused:

i want a method as part of my class to call itself until {condition} is met.

however i keep getting Object Expected on pass #2

function myClass(v1,v2)
{
this.n = 0;
this.method = function()
{
this.n = Math.floor(this.n+1);
alert('in the method, pass' + this.n);
if(this.n < 10)
window.setTimeout(function(){this.method},1000);
}
}
window.onload = function()
{
var test = new myClass('v1','v2');
test.method();
}

vwphillips
07-27-2006, 08:47 PM
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>
<title></title>
<script language="JavaScript" type="text/javascript">
<!--
var cnt=0;
function myClass(v1,v2){
this.n = 0;

this.method = function(){
this.n = Math.floor(this.n+1);
this.ref='zxc'+cnt++;
window[this.ref]=this;
alert('in the method, pass' + this.n);
if(this.n < 10){
setTimeout('window.'+this.ref+'.method()',1000);
}
}
}

window.onload = function(){
var test = new myClass('v1','v2');
test.method();
}

//-->
</script>
</head>

<body>

</body>

</html>

Beagle
07-27-2006, 08:48 PM
when you use setTimeout or setInterval, you change the executing context of the function. the "this" keyword always refers to the executing context. It's a dynamic reference to the executing frame. This is not what you want, you want a reference to the DEFINING context, you do this by creating a variable that stores "this" during deifition and using said variable.



function myClass(v1,v2)
{
var self = this;
self.n = 0;
self.method = function()
{
self.n = Math.floor(self.n+1);
alert('in the method, pass' + self.n);
if(self.n < 10)
window.setTimeout(function(){self.method},1000);
}
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum