I’m getting some odd behaviour when trying to use setInterval within an object.
Here is my code:
var Person = {
speech: null,
tryToSpeak: function ()
{
this.speech = "hello";
self.setTimeout (this.speak, 1000);
},
speak: function ()
{
// prints out undefined
console.log (this.speech);
}
}
Person.tryToSpeak ();
When speak() is run via setTimeout() it doesn’t have access to any of the objects data such as speech. What the hell is going on? Is this unavoidable behaviour?
The methods don’t carry the object information with them. You can use
.bindto …bind the method to an object:Read more about javascript this keyword