'该'和'这个'是不一样的。通过时,为什么?

时间:2017-01-27 04:47:48

标签: 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();

工作正常,并表明' &安培; '这' as' bar',但

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

不起作用,(afaik)返回foo'这个'?

如何路由

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

相同
new bar.go();

1 个答案:

答案 0 :(得分:3)

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

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