0

I am calling the method doSth2 of my class in the method doSth of this class. Now i can't access the attributes of this class. Instead I get

"Cannot read property 'idList' of undefined".

The scope must be wrong, so how do I access the attributes?

class Reset {
  constructor(nameList, idList) {
    this.nameList = nameList;
    this.idList = idList;
  }

  doSth() {
    console.log('Test' + this.idList[1]);
    return this.nameList.forEach(this.doSth2);
  }

  doSth2(element, index) {
    console.log(this.idList[index]);
  }
}

var list1 = ["Label1", "Label2", "Label3", "Label4", "Label5"];
var list2 = ["ID1", "ID2", "ID3", "ID4", "ID5"];

const handler = new Reset(list1, list2);
handler.doSth();
Nikola Kirincic
  • 3,651
  • 1
  • 24
  • 28
Bladerxdxi
  • 111
  • 1
  • 8
  • this is not a duplicate to the question mentioned, it has the issue with not passing the arguments to the `doSth2(element, index) ` method, so within that method, the `index` is undefined - this.idList[undefined]. See my fiddle for the solution, because the question is closed: https://jsfiddle.net/niklaz/x876febv/3/ – Nikola Kirincic Feb 14 '20 at 10:14
  • @niklaz No, the problem is that `this` is `undefined`. The error message pretty explicitly tells you so. – deceze Feb 14 '20 at 10:20
  • @deceze, yes, I apologize, since the `forEach` changes the scope. so as I have changed in the fiddle, it can be solved with using arrow function, because it won't change the scope of `this` then, but other than that, the arguments are not passed to the `doSth2` too. – Nikola Kirincic Feb 14 '20 at 10:30
  • @niklaz The arguments are passed just fine. It's the `this` *context* (not scope!) which gets lost by the specific way in which the callback is being passed and called. – deceze Feb 14 '20 at 10:35
  • @deceze, sorry, you are right, it was about the context of the `this`, my apologies – Nikola Kirincic Feb 14 '20 at 10:43

0 Answers0