//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();
答案 0 :(得分:3)
您可以bind
this
值,以便this
不会成为sorting
对象。
var sorting = {
sort: function(t){
console.log(that);
return that;
},
go: that.go.bind(that)
}