问题
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