2

I have a property with a simple foreach loop, inside this loop I want to use a global variable but I receive a error.

When I

Create an internal variable of the property that receives the global value to be able to use it within the loop

simpleArray = [0,1,2];
simpleArray2 = [0,1,2];

get resume() {
    let localArray = this.simpleArray;
    this.simpleArray2.forEach(function (element, index) {
        console.log(localArray);         // [0,1,2]
        console.log(this.simpleArray);   // return error undefined
    });
    return 'something';
}
juanjinario
  • 596
  • 1
  • 9
  • 24
  • `console.log(this.simpleArray)` is inside the `.forEach` callback, so `this` refers to the context of that callback, it's not the same `this` as outside. – VLAZ Jun 27 '19 at 14:45

1 Answers1

5

Use arrow function instead :

this.simpleArray2.forEach((element, index) => {
  console.log(localArray); 
  console.log(this.simpleArray); 
});
R3tep
  • 12,512
  • 10
  • 48
  • 75
  • Why does the global function allow you to work on the global context? – juanjinario Jun 27 '19 at 14:54
  • 1
    _"Try to use arrow function"_ - Care to explain why? You know, to learn something... – Andreas Jun 27 '19 at 15:02
  • 1
    Arrow functions don't manipulate the `this` keyword. Ie, Inside a regular function, this refers to the function context. If its an arrow function, it refers to the context its called within. – Riza Khan Dec 04 '20 at 23:47