//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/