user2763424
user2763424

Reputation: 69

Javascript SetTimeout Variable Access

I've looked at a few other examples for this but they are all so much more complex for what I am trying to do and don't understand how to apply them to my issue. So here's my hopefully simple problem:

function myObject(){
this.aVar  = 0;

var aFunction = function(aParam){
    console.log(aParam);
}

this.theCallerFunction = function(){
    setTimeout(function(){ aFunction(this.aVar)},5000);
}

}

The problem is that inside of aFunction, the parameter value is "undeclared", and not 0 and I am thus printing "undeclared". Can someone give me a simple solution and explanation as to what is going on here?

I've been doing object oriented c# and java for years and oo in javascript is doing my head in.

Upvotes: 0

Views: 146

Answers (1)

jfriend00
jfriend00

Reputation: 707248

You have a couple choices. You can use .bind() in modern browsers or put this into a variable you can access:

function myObject(){
    this.aVar  = 0;

    var aFunction = function(aParam){
        console.log(aParam);
    }

    // save copy of this that can be accessed from callback
    var self = this;
    this.theCallerFunction = function(){
        setTimeout(function(){ aFunction(self.aVar)},5000);
    }
}

Upvotes: 3

Related Questions