在教程后面的es6中编写代码时,我收到错误 -
class APromise {
constructor(fn) {
this.state = 'pending';
this.value = null;
this.deferred = undefined;
fn(this.resolve);
}
resolve(newValue) {
this.value = newValue; // ERROR HERE
this.state = 'resolved';
if (this.deferred) {
this.handle(this.deferred);
}
}
handle(onResolved) {
if (this.state == 'pending') {
this.deferred = onResolved;
} else {
onResolved(this.value);
}
}
then(onResolved) {
this.handle(onResolved);
}
}
const log = v => {
console.log(v);
};
const myFun = () => {
return new APromise(resolve => {
resolve('Hello World');
});
};
myFun().then(log);
错误 -
this.value = newValue;
^
TypeError: Cannot set property 'value' of undefined
但是我已经在我的es6课程中了,为什么说这是未定义的?我尝试调试并在谷歌中寻找相同的问题,但我找不到类似的问题:(
答案 0 :(得分:1)
当您将this.resolve
传递给fn
时,您需要bind将其发送到APromise
个实例:
fn(this.resolve.bind(this));
演示:
class APromise {
constructor(fn) {
this.state = 'pending';
this.value = null;
this.deferred = undefined;
fn(this.resolve.bind(this));
}
resolve(newValue) {
this.value = newValue; // ERROR HERE
this.state = 'resolved';
if (this.deferred) {
this.handle(this.deferred);
}
}
handle(onResolved) {
if (this.state == 'pending') {
this.deferred = onResolved;
} else {
onResolved(this.value);
}
}
then(onResolved) {
this.handle(onResolved);
}
}
const log = v => {
console.log(v);
};
const myFun = () => {
return new APromise(resolve => {
resolve('Hello World');
});
};
myFun().then(log);