-1

I have the following code

    var tempGameState = JSON.parse(JSON.stringify(this.gameState))
    tempGameState.forEach(function(row.bind(this), rowNum){
       ...
    }));

when I put my console.log before the forEach loop like so:

    var tempGameState = JSON.parse(JSON.stringify(this.gameState))
    console.log(this.gameState)
    tempGameState.forEach(function(row.bind(this), rowNum){
       ...
    }));

I get my game state as the output

but when I put it inside the forEach loop like so:

    var tempGameState = JSON.parse(JSON.stringify(this.gameState))
    tempGameState.forEach(function(row.bind(this), rowNum){
        console.log(this.gameState)
       ...
    }));

I get undefined.

I know this (ususally) has to do with scoping, but the javascript docs don't say anything about a new scope being created or how to handle this.

Joao Polo
  • 2,153
  • 1
  • 17
  • 26
Matt Westlake
  • 3,499
  • 7
  • 39
  • 80
  • 3
    wait, what? you can't use `row.bind(this)` as an argument name; how does this run at all? – Eevee Sep 06 '15 at 03:13

1 Answers1

3

The documentation you linked to states

If a thisArg parameter is provided to forEach(), it will be passed to callback when invoked, for use as its this value. Otherwise, the value undefined will be passed for use as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.

So, to get what you want

tempGameState.forEach(function(...){
   ...
}, this))
 ^^^^^^
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
  • the provided solution worked for me. I'm still not 100% sure why though. Doesn't the callback default to the previous state? (or the process from which called the method in the first place) – Matt Westlake Sep 06 '15 at 03:23
  • 1
    _Doesn't the callback default to the previous state?_ without a `thisArg` **The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.** - the rules being - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this – Jaromanda X Sep 06 '15 at 03:25
  • Thanks for the link.. I understand so much more about javascript now. – Matt Westlake Sep 06 '15 at 05:36