javascript - `this` 对象在使用promise时未定义

标签 javascript node.js ecmascript-6

<分区>

在下面的示例中,当我运行此代码时,调用启动函数时,仅在 _one 函数中定义了 this 。当继续执行下一个函数 _two 时,this 未定义。有什么解释吗?以及如何解决这个问题? 提前致谢。

'use strict';

class MyClass {
    constructor(num) {
        this.num = num;
    }

start() {
    this._one()
    .then(this._two)
    .then(this._three)
    .then(this._four)
    .catch((err) => {
        console.log(err.message);
    });
}

_one() {
    console.log('num: ' + this.num);
    return new Promise((resolve, reject) => {
        resolve();
    });
}
_two() {
    console.log('num: ' + this.num);
    return new Promise((resolve, reject) => {
        resolve();
    });
}
_three() {
    console.log('num: ' + this.num);
    return new Promise((resolve, reject) => {
        resolve();
    });
}
_four() {
    console.log('num: ' + this.num);
    return new Promise((resolve, reject) => {
        resolve();
    });
}
}


let myClass = new MyClass(4);
myClass.start();

最佳答案

将 promise 链修改为:

start() {
    this._one()
    .then(this._two.bind(this))
    .then(this._three.bind(this))
    .then(this._four.bind(this))
    .catch((err) => {
        console.log(err.message);
    });
}

bind() 将修改处理程序以绑定(bind)正确的this 对象(MyClass 的实例)。您将实现对 MyClass 实例的方法调用

按照您的初始场景,Promise 将调用处理程序(_two_three)作为常规函数,在 Strict 中mode 会将 this 设为 undefined

See here有关 bind() 的更多详细信息。

关于javascript - `this` 对象在使用promise时未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35481367/

相关文章:

javascript - 存储 JS 对象以及原型(prototype)、实例类型等

node.js - Alexa 技能异步等待从 DynamoDB 获取数据

javascript - 如何在 Jest 的 xyz.test.js 中导入 ".mjs"模块?

node.js - Flash 消息未在 Node.js 中显示

javascript - 什么是 .esm.js 文件以及格式为 : 'es' in rollup. js 的内容?

javascript - 导出 React 组件最合乎逻辑的方法是什么?

javascript - Angular 发送事件到指令

javascript - 'array[array.length - 1] = array.pop()' 会产生未定义的行为吗?

angular - 检测元素是否在 Angular2 中具有焦点

javascript - 如何在 Cypress 中创建命令