javascript - 'that' 传递时与 'this' 不一样,为什么?

标签 javascript class this

//class bar
//(construtor)
go(res, err){
    //functions that use 'this'
    console.log(this); 
} 
foo(article){ 
    //do stuff
    var that = this;
    var sorting = {
        sort: function(t){
            //do stuff
            console.log(that); //looks exactly like 'bar'
            return that;
        },
        go: that.go //ERROR: want this.go, got foo.sorting
    }
    return sorting;
}

为什么

new bar.foo('x').sort();

工作正常并将“that”和“this”显示为“bar”,但是

new bar.foo('x').go();

不起作用并且(据我所知)返回 foo 的“this”?

如何路由

new bar.foo('x').go();

与相同

new bar.go();

最佳答案

你可以bind this 值,以便 this 不会成为 sorting 对象。

var sorting = {
    sort: function(t){
        console.log(that);
        return that;
    },
    go: that.go.bind(that)
}

关于javascript - 'that' 传递时与 'this' 不一样,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41887100/

相关文章:

javascript - Chrome 应用程序 : Why can't i modify the page?

python - 将 Python 类变量设置为等于类函数的输出

javascript - 如何在 JS 类中拥有 .on ('click' ) 事件

c++ - 继承返回 *this 的成员函数

algorithm - 我应该采取什么步骤来识别这个算法

JavaScript 模式 : calling multiple method

javascript - 在 POST 之前禁用“取消”按钮

javascript - ractive 中条件部分的正确语法是什么?

java - class.class 代表什么

c# - 'this' 关键字作为属性