0

Using angular 5, I call denoFormat(item["DENOMINATION"]) I get the following error stack

vendor.91392bd4e66ade432f98.bundle.js:1 ERROR TypeError: Cannot read property 'denoFormat' of undefined at main.e31e50ee66f46596cba1.bundle.js:1 at Function.g.map.g.collect (vendor.91392bd4e66ade432f98.bundle.js:1) at e._next (main.e31e50ee66f46596cba1.bundle.js:1) at e.T14+.e.__tryOrUnsub (vendor.91392bd4e66ade432f98.bundle.js:1) at e.T14+.e.next (vendor.91392bd4e66ade432f98.bundle.js:1) at e.T14+.e._next (vendor.91392bd4e66ade432f98.bundle.js:1) at e.T14+.e.next (vendor.91392bd4e66ade432f98.bundle.js:1) at e.L8VJ.e._next (vendor.91392bd4e66ade432f98.bundle.js:1) at e.T14+.e.next (vendor.91392bd4e66ade432f98.bundle.js:1) at XMLHttpRequest.s (vendor.91392bd4e66ade432f98.bundle.js:1)

If I were to use item["DENOMINATION"] no error occurs. Can someone explain what's going on?

 var _data =  [ { DENOMINATION: 0, FIT: 0, UNFIT: 0},
        { DENOMINATION: 1, FIT: 2157, UNFIT: 1842},
        { DENOMINATION: 2, FIT: 2455, UNFIT: 2031 }
  ];

  var arr = [];
  arr.push(_.map(this._data ,function(item){
    if (((item["FIT"] + item["UNFIT"]) != 0) && (item["DENOMINATION"] <= 5)){
      return {"name": this.denoFormat(item["DENOMINATION"]) ,"series": [
      {
        "name": "FIT",
        "value": item["FIT"]
      },
      {
        "name": "UNFIT",
        "value": item["UNFIT"]
      }
    ]}
  } else{
    return;
}
}));
      denoFormat(n){
        var val;
        switch (n){
          case 0:
          val = 1000;
          break;
          case 1:
          val = 5000;
          break;
          etc.
        }
        return val;
      }
Vikas
  • 11,859
  • 7
  • 45
  • 69
LSTM
  • 128
  • 8
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – ConnorsFan Jul 09 '18 at 16:23

1 Answers1

3

In this case, you have to use an arrow function to prevent the scope changing.

arr.push(_.map(this._data , (item) => {
    // ...
    this.denoFormat()
    //...
}
JSON Derulo
  • 9,780
  • 7
  • 39
  • 56