forEach的callback中this指向问题

438 阅读1分钟

代码如下

export class Test {
    private pars;

    componentDidMounted() {
        this.get();
    }
    public get() {
        this.pars = [1, 2, 3, 4, 5, 6, 7];
        const p1 = this.post([12, 3, 4, 5, 6, 6]);
    }

    private post(a) {
        a.forEach(item => {
            // 这里this.pars报错,整个应用直接崩掉了
            const newDistance = this.pars[0];

            item += newDistance;
        });
    }
}

排查思路:

1.看看这个this到底是什么?

加上console.log(this);

private post(a) {
        a.forEach(item => {
            // 这里this.pars报错,整个应用直接崩掉了
            const newDistance = this.pars[0];
            console.log(this);
            item += newDistance;
        });
    }

打印出来的为undefined,this为undefined自然是没有pars这个属性的。

2.猜测为啥是undefined

猜测1:该函数不为箭头函数,this没有绑定为Test类实例。这个猜想我起初也是不信的,可以参考之前为写过的this指向。但是还是去试了一下,将该函数改为箭头函数,打印出来的依然是undefined.这个时候有点懵逼了 猜测2:在类中public函数调用另一个private函数,找不到this指向,但是在尝试其他的private函数之后。证明这个猜想也是错误的。 猜想3:forEach中的callback中的this指向哪?这个猜想的依据是,这个this是写在函数中的,根据之前掌握的知识,函数中的this指向是在函数调用时确定的,所以果断google搜索,forEach中this指向哪。得到答案developer.mozilla.org/zh-CN/docs/…

image.png 后来再forEach外打印this,在把this传进去,都拿到了想要的结果。顺利解决

心得:

1.猜想,要学会猜。猜完再验证就是了。 2.google能力。人不可能记住所有的知识点,要有学习能力。 3.总结:正如我现在在做的事。