PDA

View Full Version : Problems with self calling object function



Bob90
03-21-2007, 12:26 AM
If anyone can help with this I woulg be grateful.
I think this is the offending line:

setTimeout("this.walk()",5000)

Here is the full code:

<script>
function person()
{
this.walk = walk;
this.move=0;
this.position = 0;
}

function walk()
{
this.position += 2;
if(this.position<= 10)
{
alert("Walking")
setTimeout("this.walk()",5000)
}
else
{
alert("Finished walking")
}
}

James = new person();
James.walk();
</script>

Something wrong with calling the same object function from within itself?

Cheers

Twey
03-21-2007, 08:47 AM
<script>The type attribute is required.
function person()
...
James = new person();The convention for constructor functions is that they start with a capital, and the convention for variables is that they don't. In English we use capitals for proper nouns; in Javascript, we don't. :)
this.walk = walk;This is what prototypes are for.
setTimeout("this.walk()",5000)If you pass a string to setTimeout() (which is bad practice), it will be evaluated in the global scope, so this isn't defined. Instead, you can store a reference to the current object in a variable and use a closure:
<script type="text/javascript">
function Person() {
this.move =
this.position =
0;
}

Person.prototype.walk = function() {
this.position += 2;
if(this.position <= 10) {
alert("Walking");
var me = this;
setTimeout(function() { me.walk(); }, 5000);
} else
alert("Finished walking")
};

var james = new Person();
james.walk();
</script>

Bob90
03-21-2007, 09:23 AM
Hey Twey,

Thanks for the help.
I have never used anything but strings in setIntervals and setTimeouts :S, so that is a real education.

One little thing: you say it is evaluated in the global scope, yet you initiate the variable 'me' with var, making it local. Or am I confused?

Thanks again.:)

Twey
03-21-2007, 09:33 AM
One little thing: you say it is evaluated in the global scope, yet you initiate the variable 'me' with var, making it local.A closure is able to access the local variables in the scope in which it was created no matter where it's called. That's the defining feature of a closure. If we made "me" global, it could lead to race conditions.