我不确定为什么在这段代码片段中,open方法中的最后一个'this'返回一个空对象。在箭头函数'this'之外返回正确的信息。使用箭头函数应该基本上将它绑定到我想的相同'this',但它只是返回undefined ...
'wrap'是我的异步代码的包装函数。
let Client = wrap(async function (host, opts) {
if (!(this instanceof Client)) {
return new Client(host, opts);
}
this.host = host;
this.opts = opts;
await this.open();
return this;
});
Client.prototype.open = wrap(async function () {
// Omitted most code here as it doesn't influence the problem at all.
console.log(this); // Works
(function (test) {
console.log(test); // Works
})(this);
await new Promise(function (resolve, reject) {
console.log(this); // Obviously Undefined
});
await new Promise(function (resolve, reject) {
console.log(this); // Works, but is ugly.
}.bind(this));
await new Promise((resolve, reject) => {
console.log(this); // Returns empty object {}. Why?
});
});
如果我将逻辑放在主客户端代码中,或者不使用原型,一切正常。但第二个我原型,它打破了。