在foreach循环中,“this”未定义。

52

我正在编写一些TypeScript代码并迭代一个数组。在循环内部,我尝试访问'this'对象以进行一些处理,如下:

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],但在循环内部,它是未定义的。为什么会这样?有什么解决方法吗?

3个回答

108

您需要使用箭头函数

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

或者使用bind 方法

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

原因是当把一个普通的函数作为回调函数传递时,当它被调用的时候,this实际上并没有被保留。
我之前提到的两种方法将确保函数未来执行时保留适当的this作用域。


很好的解释。 - Ziggler

17

this作为回调函数的参数添加。

在Angular中,使用}, this);代替}.bind(this));应该可以解决这个问题。

因此,代码应该像这样:

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

有时候,Stack Overflow 让我感到沮丧,但大多数情况下它会帮助我解决问题,就像这个问题一样。 - Ziggler
太棒了,喜欢这个。 - Ajv2324

2

试试这个:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接