0

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.

1 Answer 1

3

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.