javascript - 无法在 es6 类中设置未定义的属性 'value'

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

最佳答案

当你将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);

关于javascript - 无法在 es6 类中设置未定义的属性 'value',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46618945/

相关文章:

javascript - eslint 脚本因meteor run npm eslint 失败

javascript - 您必须在调用 logIn 之前初始化 FacebookUtils

javascript - 延迟 Javascript 悬停 Action

javascript - for..of 循环中的yield * 和yielding 之间的区别?

javascript - ES6 箭头函数和 array.map

javascript - Mean.js 不工作。无法连接到 MongoDB

javascript - 从 React-Native 应用程序中的另一个类访问静态变量?

javascript - React 组件 require.default 未定义

javascript - Node js 不断重定向 - 中间件

angularjs - Linux Azure Web 应用程序上的 node.js 部署出错