当作为参数传递的forEach为什么不CONSOLE.LOG工作? [英] Why doesn't console.log work when passed as a parameter to forEach?

查看:531
本文介绍了当作为参数传递的forEach为什么不CONSOLE.LOG工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这仅仅是出于好奇,但做任何你有一个想法,为什么这code将无法正常工作?

This is just out of curiosity, but do any of you have an idea why this code won't work?

[1, 2, 3, 4, 5].forEach(console.log);

// Prints 'Uncaught TypeError: Illegal invocation' in Chrome

在另一方面,这似乎很好地工作:

On the other hand, this seems to work fine:

[1, 2, 3, 4, 5].forEach(function(n) { console.log(n) });

所以...?

推荐答案

其实作为@SLaks指出,执行console.log好像是用这个在内部,当它通过作为一个参数这个现指的数组实例。

Actually as @SLaks pointed out, console.log seems to be using this internally and when it's passed as a parameter this now refers to the array instance.

该解决方法很简单:

变种C = console.log.bind(控制台);
[1,2,3,4,5] .forEach(C);

这篇关于当作为参数传递的forEach为什么不CONSOLE.LOG工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆