且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

'this'在foreach循环中未定义

更新时间:2022-04-18 22:09:41

您需要使用或使用绑定方法:

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

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

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