无法设置属性'值'在es6类中未定义的

时间:2017-10-07 10:00:11

标签: javascript node.js ecmascript-6

在教程后面的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课程中了,为什么说这是未定义的?我尝试调试并在谷歌中寻找相同的问题,但我找不到类似的问题:(

1 个答案:

答案 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);