'this'在foreach循环中未定义

use*_*775 28 typescript typescript1.8 typescript2.0

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

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

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

Nit*_*mer 59

您需要使用箭头功能:

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

或者使用bind方法:

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

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


rc.*_*ari 7

添加this作为回调的参数。

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

因此,应如下所示:

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