'this'在foreach循环中未定义 [英] 'this' is undefined inside the foreach loop

查看:338
本文介绍了'this'在foreach循环中未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些打字稿代码并迭代一个数组.在循环内部,我尝试访问"this"对象以进行一些处理,例如:

I am writing some typescript code and iterating an array. Inside the loop, I am trying to access 'this' object to do some processing as:

console.log('before iterate, this = ' +this);
myarray.days.forEach(function(obj, index) {
    console.log('before transform, this : ' + this);
    this.datePipe.transform...
});

但是失败了,因为它抱怨'this'是不确定的 'this'对象在循环之前/循环之外正确打印为[object object],但在循环内部未定义.这是为什么?对此有什么解决办法?

but this fails, as it complains that 'this' is undefined 'this' object prints correctly as [object object] before/outside the loop, but inside the loop, it is undefined. Why is that? And what is the fix for that?

推荐答案

您需要使用或使用绑定方法:

myarray.days.forEach(function(obj, index) {
    console.log('before transform, this : ' + this);
    this.datePipe.transform...
}.bind(this));

原因是当将常规函数作为回调传递时,实际上未保留this.
我上面提到的两种方法将确保保留正确的this范围,以供将来执行该功能.

The reason is that when passing a regular function as a callback, when it is invoked the this is not actually preserved.
The two ways which I mentioned above will make sure that the right this scope is preserved for the future execution of the function.

这篇关于'this'在foreach循环中未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆