2

I am trying to access a outer variable inside a function within a function, but it is showing the variable as undefined in my debugger:

export class TestClass {
  someObj = [ { id=1 }];

  changeData() {
    const someId = 1;
    const test = {
       attr: function() { return (this.somObj.find(x => x.id === someId ));   }
    };
  }
}

this.someObj is undefined. Is it possible to accomplish this?

elesh.j
  • 192
  • 1
  • 3
  • 15

2 Answers2

4

You misspelled this.somObj.

You have to refer this with an other variable before:

 changeData() {
    const someId = 1;
    const that = this;
    const test = {
       attr: function() { return (that.someObj.find(x => x.id === someId ));   }
    };
  }

As stated by someone else, you can also use an arrow function:

attr: () => { return (this.someObj.find(x => x.id === someId )); }
Maarti
  • 3,600
  • 4
  • 17
  • 34
1
someObj = [ { id=1 }];

did you mean:

someObj = [ { id:1 }];

?

Jake11
  • 801
  • 2
  • 11
  • 24