使用 Node.js 的 Q library ,当我尝试将对象原型(prototype)函数传递给 .then
时 promise 中的解析器,它正在丢失 this
的上下文:
Foo.prototype.outsideResolve = function() {
var that = this;
return q.Promise(function(resolve, reject) {
console.log(that); // {data: "foo"}
resolve();
});
};
Foo.prototype.insideResolve = function() {
var that = this;
return q.Promise(function(resolve, reject) {
console.log(that); // undefined
resolve();
});
};
Foo.prototype.async = function() {
var foo = this;
return q.Promise(function(resolve, reject) {
foo.outsideResolve()
.then(foo.insideResolve)
.then(resolve)
.fail(reject)
.done();
});
};
为什么会发生这种情况?这是预期的行为吗?你不应该能够在 Promise 解析中调用原型(prototype)函数吗?有办法解决这个问题吗?
最佳答案
this
不是静态的东西。它可以根据使用 this
的函数被调用的内容而改变。在某些情况下,这可能是您刚刚调用 new 的对象,但在本例中,它不是。
当您从 Promise 链到达 foo.insideResolve
时,ThisBinding 就会丢失。为了解决这个问题,您可以使用 Function.prototype.bind 方法,该方法采用可变数量的参数 - 第一个参数是您想要绑定(bind)的 this
上下文要使用的函数,其他是部分应用的参数。 bind
函数返回一个函数,该函数在调用时将 this
和参数传递给原始函数。
简而言之:
使用foo.insideResolve.bind(foo)
而不是foo.insideResolve
。
关于javascript - 不能将原型(prototype)函数放入promise解析中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31299715/