Javascript 角度4:无法读取类变量的属性

Javascript 角度4:无法读取类变量的属性,javascript,angular,Javascript,Angular,我正在学习在angular 4中创建新应用程序,现在在我的一个文件中 export class AppComponent { str: string = ""; arr = []; constructor(private elemRef: ElementRef, private rend: Renderer, private objComp: AppObjComponent) { } @HostListener('keyup', ['$event']) textKeyPre

我正在学习在angular 4中创建新应用程序,现在在我的一个文件中

export class AppComponent {
  str: string = "";
  arr = [];
  constructor(private elemRef: ElementRef, private rend: Renderer, private objComp: AppObjComponent) {

  }
  @HostListener('keyup', ['$event']) textKeyPressed(ev) {
      console.log(this.elemRef);
      if (ev) {
        this.str = ev.target.value;
        console.log(this.str);
        this.objComp.obj.forEach(function(elem, index) {

          if (elem.includes(this.str)) {
            this.arr.push(this.str);
          }

        })
      }
编译时,它在浏览器上编译得很好,但会抛出错误

AppComponent_Host.ngfactory.js? [sm]:1 ERROR TypeError: Cannot read property 'str' of undefined
这是哪条线

if(elem.includes(this.str))
但是如果我使用console.log打印它,它将在同一个函数中打印

console.log(this.str);

我不知道为什么它会对this.str抛出错误。如果我对this.str行进行注释,它也会对this.arr抛出错误。不确定为什么它无法访问类变量。

您的forEach中的
this
不是您的类的
this
。 要保留类的上下文,请使用胖箭头:

this.objComp.obj.forEach((elem, index) => {
    if (elem.includes(this.str)) {
       this.arr.push(this.str);
    }
})
或者使用forEach的
thisArg
参数(请参阅),该参数告诉:

如果为forEach()提供了thisArg参数,则该参数将用作 回调是这个值。否则,未定义的值将用作 它就是这个值。回调最终可观察到此值的 根据通常的规则确定,用于确定该位置 通过一个函数

因此:


您需要在for each中使用箭头函数,或者将作用域绑定到函数(最好是第一个选项)

尝试:
let that=this;this.objComp.obj.forEach(function(elem,index){if(elem.includes(that.str)){}})
并让我知道,尽管您的答案在技术上是正确的,但在现代js中,对于这种情况,这不是一个好的实践,最好使用arrow函数
this.objComp.obj.forEach(function(elem, index) {
    if (elem.includes(this.str)) {
       this.arr.push(this.str);
    }
}, this ) // this added here