在成员函数回调中获取对象

mis*_*t92 7 javascript callback

我有一个带有方法的对象,我想将其作为回调传递给函数.但是,在回调内部,this不再引用我的对象.为什么不?

我很熟悉在传递函数文字时使用变量来解决问题:

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

        console.log(this);

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

在这种情况下我该如何解决?

var obj = {
    b: function () {
        setTimeout(this.callback, 100);
    },
    callback: function () {
        console.log(this); // =(
    }
};
Run Code Online (Sandbox Code Playgroud)

hug*_*omg 9

是的,this在Javascript中可能有点棘手.问题是它的值取决于你如何调用函数.

obj.callback(); //ok

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

通常的解决方法是传递一个像b)中所做的包装回调,除了me变量的通用名称that(你有时也看到self)

var that = this;
setTimeout( function(){ return that.callback(); }, 300);
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用函数中的bind方法

setTimeout( this.callback.bind(this) , 300)
Run Code Online (Sandbox Code Playgroud)

请注意,IE 8中不支持绑定(在这种情况下您可能需要填充程序).


更多:

使用回调和闭包时,在Javascript中维护对"this"的引用