Asher Saban
Asher Saban

Reputation: 4793

how to reach variables of an object that called a function which called a function

i have the following object. i´m trying to reach the variable b from inside the callback of setTimeout but it doesn't work. i know that the callback of setTimeout only knows the variables of the its surrounding function, so how can i reach the this.b? thank you!

function someFunc() {
    this.a = 10;
    this.b = 20;
    this.func = function() {
                this.c = 50;
        console.log("a = " + this.a);  //works
        var time = setTimeout(function() {
            console.log("b = " + someFunc.b);   //this.b doesn't work
            console.log("C = " + this.c);  //why this doesn't work also? says undefined
        },1000);
    }
}

var m = new someFunc();
m.func();

Upvotes: 1

Views: 208

Answers (3)

m3kh
m3kh

Reputation: 7941

Also you can use something like this to execute your anonymous function within your object scope:

function createDelegate(instance, callback) {
    return function () {
        callback.apply(instance, arguments);
    };
}

function someFunc() {
    this.a = 10;
    this.func = function() {
        this.c = 50;
        console.log("a = " + this.a);
        var time = setTimeout(createDelegate(this, function() {
            console.log("b = " + someFunc.b);
            console.log("C = " + this.c);
        }),1000);
    }
}

someFunc.b = 20;

var m = new someFunc();
m.func();

Upvotes: 0

ziesemer
ziesemer

Reputation: 28697

function someFunc() {
    this.a = 10;
    this.b = 20;
    var mySomeFunc = this;
    this.func = function() {
        console.log("a = " + this.a);  //works
        var time = setTimeout(function() {
            console.log("b = " + mySomeFunc.b);
        },1000);
    }
}

Upvotes: 3

SLaks
SLaks

Reputation: 887453

this does not refer to the function object; it refers to the context in which it was called. (your m variable)

someFunc.b is a propertyo f the function itself (like a static property).
You need to save a reference to the outer this in a variable.

Upvotes: 2

Related Questions