为什么console.log非法被调用为函数参数?

Jan*_*roň 2 javascript google-chrome

当我尝试

[1,2,3].forEach(alert);
Run Code Online (Sandbox Code Playgroud)

它会按预期打开数组中每个项目的消息框.

但是,当我尝试

[1,2,3].forEach(console.log);
Run Code Online (Sandbox Code Playgroud)

我收到以下错误

Uncaught TypeError: Illegal invocation
Run Code Online (Sandbox Code Playgroud)

为什么?

Nie*_*sol 7

就我个人而言Invalid calling object.

看,[1,2,3].forEach(console.log)本质上是迭代数组和运行的每个项目的简便方法console.log.call(theArray,theItem).但是,console.log要求this是类型的对象Console,因此错误.

尝试 [1,2,3].forEach(function(i) {console.log(i);})

  • 优秀!我设法通过将控制台传递到它的上下文来解决它,如你所解释的那样:`[1,2,3] .forEach(console.log.bind(console));`你能否把它添加到你的答案中帮助其他人遇到这个问题? (2认同)