Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get object in member function callback

I have an object with a method that I’d like to pass to a function as a callback. However, inside the callback, this no longer refers to my object. Why not?

I’m familiar with using a variable to get around the problem when passing a function literal:

var obj = {
    a: function () {
        var me = this;

        console.log(this);

        setTimeout(function () {
            console.log(this); // Not obj
            console.log(me);   // This works!
        }, 100);
    }
};

How can I fix it in this case?

var obj = {
    b: function () {
        setTimeout(this.callback, 100);
    },
    callback: function () {
        console.log(this); // =(
    }
};
like image 913
missingcat92 Avatar asked Nov 19 '11 02:11

missingcat92


1 Answers

Yes, this can be kind of tricky in Javascript. The problem is that its value depends on how you call the function.

obj.callback(); //ok

var f = obj.callback;
f(); //does not look like a method call
     //Javascript does not pass the this!

The usual workaround is passing a wrapper callback like you did in b), except that the common name for the me variable is that (you sometimes see self too)

var that = this;
setTimeout( function(){ return that.callback(); }, 300);

The other alternative is to use the bind method from functions

setTimeout( this.callback.bind(this) , 300)

Note that bind is not supported in IE 8 (you might need a shim in that case).


For more:

Maintaining the reference to "this" in Javascript when using callbacks and closures

like image 60
hugomg Avatar answered Nov 17 '22 11:11

hugomg