Why do console.log() polyfills not use Function.apply()?

好久不见. 提交于 2019-12-22 05:06:16

问题


I've been looking at some of the popular console.log() wrappers/polyfills:

  • Paul Irish's
  • Ben Alman's
  • Craig Patik's

I notice that all of them accept multiple arguments, but they all do something like this:

console.log(arguments);

Which results in output like this (in Chrome):

Whereas, at least in a modern browser like Chrome or Firefox, console.log() also accepts multiple arguments, so that this would produce (IMHO) superior output:

console.log.apply(console, arguments)

Which results in output like this (in Chrome):

Is there any particular reason why I should avoid using console.log.apply() with multiple arguments? Or this this just a matter of taste or saving bytes?


回答1:


I would personally suggest that you only use .apply() when you have to: .apply() is the only way to pass an array as the arguments of a function. If you don't need to pass an array, then just use console.log(). It is less verbose and it is a direct invocation.




回答2:


Please note that apply takes an array of arguments!

So calling console.log(args) have to be console.log.apply(console, [args]), not console.log.apply(console, args) to behave equal - in your example each item in array becomes his very own argument in apply.

On the other hand you may also call console.log("foo", "bar", $("body"))



来源:https://stackoverflow.com/questions/11584218/why-do-console-log-polyfills-not-use-function-apply

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!