【问题标题】:"this" is undefined when function is passed as argument in chain [duplicate]当函数作为链中的参数传递时,“this”未定义[重复]
【发布时间】:2016-02-06 04:23:47
【问题描述】:

我的问题的简单示例

考虑以下情况,我在c 的承诺链中使用了一些函数(ab):

class SomeClass {
    constructor(){
        this.v1 = 1;
        this.v2 = 2;
    }

    a() {
        return new Promise((resolve, reject) => {
            console.log('a', this.v1);  // Do something with `this`
            resolve();
        });
    }

    b() {
        return new Promise((resolve, reject) => {
            console.log('b', this.v2);   // Do something with `this`
            resolve();
        });
    }

    c() {
        return this.a().then(this.b);   // passing b as argument
    }
}

当我调用c 并运行承诺链时,thisb 中未定义。

const sc = new SomeClass();

sc.c().then(() =>{
    console.log('done')
}).catch((error) => {
    console.log('error', error);
});

输出:

a 1
error [TypeError: Cannot read property 'v2' of undefined]

我知道箭头函数继承了外部this,但我不确定为什么它是未定义的,因为我是从c 调用它。

【问题讨论】:

    标签: javascript ecmascript-6 babeljs


    【解决方案1】:

    问题出在这里:

    this.a().then(this.b)
    

    因为this.b 检索到的结果函数与this 解除绑定(您实际上并未按照问题中所述的方式调用它)。

    您可以通过使用箭头方法来保留范围,以与其余代码一致的方式解决它:

    this.a().then(obj => this.b(obj))
    

    或者您可以使用.bind 来实现类似的结果:

    this.a().then(this.b.bind(this))
    

    【讨论】:

    • 当您拥有一长串类函数时,哪个选项更受欢迎?
    • 我会说这是“一个中的六个,另一个中的六个”的选择。我更喜欢使用箭头函数作为范围保留机制,它肯定与您的其余代码一致。
    猜你喜欢
    • 1970-01-01
    • 2015-03-16
    • 2019-10-18
    • 2020-07-13
    • 1970-01-01
    • 2019-04-25
    • 2013-08-13
    • 2017-02-15
    • 2021-10-28
    相关资源
    最近更新 更多