【问题标题】:'this' is undefined inside the foreach loop'this' 在 foreach 循环中未定义
【发布时间】:2017-09-29 04:23:00
【问题描述】:

我正在编写一些打字稿代码并迭代一个数组。在循环内部,我试图访问“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


    【解决方案1】:

    您需要使用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 范围以供将来执行该函数。

    【讨论】:

      【解决方案2】:

      添加this 作为回调参数。

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

      因此,应该如下所示:

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

      【讨论】:

        【解决方案3】:

        试试这个:

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

        【讨论】:

          猜你喜欢
          • 2019-01-02
          • 2020-08-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-08-18
          • 2020-11-03
          相关资源
          最近更新 更多