Q promise 的范围如何运作?据我所知,“then”的回调是由窗口调用的,就像setTimeout一样。
在此示例中(仅是了解其工作原理的示例):
var getFileText = function() {
var deferred = Q.defer();
Server.readFile("foo.txt", "utf-8", function (error, text) {
if (error) {
deferred.reject(new Error(error));
} else {
deferred.resolve(text);
}
});
return deferred.promise;
};
var Foo = function () {
getFileText().then(this.showFile);
};
Foo.prototype.showFile = function(text) {
this.text = text;
console.log(text);
};
var foo = new Foo();
为了在foo实例中包含文本,我正在使用bind:
var Foo = function () {
getFileText().then(this.showFile.bind(this));
};
还有其他办法吗?
最佳答案
您正在寻找上下文。
好吧,在全局范围内,是的。使用undefined
作为thisArg
调用它is specified。
只有冗长的变量,带有引用实例的变量:
var that = this;
getFileText().then(function(text) {
that.text = text;
// or even longer:
// that.showFile(text);
});