Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript forEach作用域_Javascript_Foreach - Fatal编程技术网

javascript forEach作用域

javascript forEach作用域,javascript,foreach,Javascript,Foreach,我有以下代码 var tempGameState = JSON.parse(JSON.stringify(this.gameState)) tempGameState.forEach(function(row.bind(this), rowNum){ ... })); 当我将我的console.log放在forEach循环之前时,如下所示: var tempGameState = JSON.parse(JSON.stringify(this.gam

我有以下代码

    var tempGameState = JSON.parse(JSON.stringify(this.gameState))
    tempGameState.forEach(function(row.bind(this), rowNum){
       ...
    }));
当我将我的console.log放在forEach循环之前时,如下所示:

    var tempGameState = JSON.parse(JSON.stringify(this.gameState))
    console.log(this.gameState)
    tempGameState.forEach(function(row.bind(this), rowNum){
       ...
    }));
    var tempGameState = JSON.parse(JSON.stringify(this.gameState))
    tempGameState.forEach(function(row.bind(this), rowNum){
        console.log(this.gameState)
       ...
    }));
我得到我的游戏状态作为输出

但当我把它放在forEach循环中时,就像这样:

    var tempGameState = JSON.parse(JSON.stringify(this.gameState))
    console.log(this.gameState)
    tempGameState.forEach(function(row.bind(this), rowNum){
       ...
    }));
    var tempGameState = JSON.parse(JSON.stringify(this.gameState))
    tempGameState.forEach(function(row.bind(this), rowNum){
        console.log(this.gameState)
       ...
    }));
我得到未定义的


我知道这(通常)与作用域有关,但不要说正在创建新的作用域或如何处理它。

您链接到的文档说明

如果为forEach()提供了thisArg参数,则在调用时会将其传递给回调,以用作其this值。否则,值
未定义
将被传递以用作其此值。回调最终可观察到的
this
值是根据确定函数所见this值的常规规则确定的

所以,为了得到你想要的

tempGameState.forEach(function(...){
   ...
}, this))
 ^^^^^^

等等,什么?不能使用
行.bind(this)
作为参数名;这到底是如何运行的?提供的解决方案对我很有效。但我仍然不能100%确定原因。回调不是默认为以前的状态吗?(或者首先调用该方法的进程)回调不是默认为前一个状态吗?如果没有
thisArg
,回调最终可观察到的该值将根据确定函数看到的该值的常规规则确定。-规则是-谢谢你的链接。。我现在对javascript有了更多的了解。