'this'在foreach循环中未定义

问题描述 投票:16回答:3

我正在编写一些打字稿代码并迭代一个数组。在循环内部,我试图访问'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],但在循环内部,它是未定义的。这是为什么?那是什么解决方案?

typescript typescript2.0 typescript1.8
3个回答
51
投票

你需要使用arrow function

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

或者使用bind method

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

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


5
投票

添加this作为回调参数。

添加}, this);而不是}.bind(this));应解决Angular中的问题。

因此,应该看起来像:

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

1
投票

试试这个:

myarray.days.forEach( (obj) => {
    console.log('before transform, this : ' + this);
    this.datePipe.transform...
});
© www.soinside.com 2019 - 2024. All rights reserved.