'this' 在 foreach 循环中未定义

'this' is undefined inside the foreach loop

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

您需要使用 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 范围。

添加this作为回调参数。

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

因此,应该看起来像:

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

试试这个:

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