我想在Javascript中创建一个对象。
其中一个方法应该执行一个Promise链。链中的每个方法都必须访问对象的成员变量config。
问题是,PromiseMethod2
中的this
运算符被更改了,我无法访问config变量(在PromiseMethod1
中它可以正常工作)。
这是我的代码:
var SomeObject(config) {
var that = this;
that.config = config;
}
SomeObject.prototype.SomeMethod = function() {
var that = this;
that.PromiseMethod1()
.then(that.PromiseMethod2)
.catch(console.error);
}
SomeObject.prototype.PromiseMethod1 = function() {
var that = this;
config = that.config;
return SomePromise();
}
SomeObject.prototype.PromiseMethod2 = function(someParams) {
var that = this;
config = that.config;
params = someParams;
return SomePromise();
}
var someObject = new SomeObject(someConfig);
someObject.SomeMethod().then(function () {
console.log('Done!');
}
我希望使用委托方法来替代直接执行链中的方法:
that.PromiseMethod1().then(function(response) { return that.PromiseMethod2(that, response); };
我无法使用 bind
方法,因为它似乎在回调函数执行时被重新绑定。
有解决方法吗?
为什么 PromiseMethod1
和 PromiseMethod2
之间存在差异?
SomePromise
? - Kiril