typescript 'this' 在 foreach 循环中未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43724426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:43:10  来源:igfitidea点击:

'this' is undefined inside the foreach loop

typescripttypescript2.0typescript1.8

提问by user1892775

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:

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

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

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?

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

回答by Nitzan Tomer

You need to either use an arrow function:

您需要使用箭头函数

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

Or use the bind method:

或者使用绑定方法

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

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

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

回答by rc.adhikari

Add the thisas a parameter for callback.

添加this作为回调的参数。

Adding }, this);instead of }.bind(this));should resolved issue in Angular.

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

Thus, should look like:

因此,应该看起来像:

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

回答by Eray T

Try this:

尝试这个:

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