简体   繁体   English

为什么console.log()polyfill不使用Function.apply()?

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

I've been looking at some of the popular console.log() wrappers/polyfills: 我一直在看一些流行的console.log()包装器/ polyfill:

I notice that all of them accept multiple arguments , but they all do something like this: 我注意到它们都接受多个arguments ,但它们都是这样的:

console.log(arguments);

Which results in output like this (in Chrome): 这导致像这样的输出(在Chrome中):

<code> console.log(['foo','bar',$('body')])</ code>

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: 然而,至少在像Chrome或Firefox这样的现代浏览器中, console.log()也接受多个参数,这样就可以产生(恕我直言)出色的输出:

console.log.apply(console, arguments)

Which results in output like this (in Chrome): 这导致像这样的输出(在Chrome中):

<code> console.log.apply(console,['foo','bar',$('body')])</ code>

Is there any particular reason why I should avoid using console.log.apply() with multiple arguments? 是否有任何特殊原因可以避免使用带有多个参数的console.log.apply() Or this this just a matter of taste or saving bytes? 或者这仅仅是品味或节省字节的问题?

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. 我个人建议您只在必须使用.apply()时: .apply()是将数组作为函数参数传递的唯一方法。 If you don't need to pass an array, then just use console.log() . 如果您不需要传递数组,那么只需使用console.log() It is less verbose and it is a direct invocation. 它不那么冗长,而且是直接调用。

Please note that apply takes an array of arguments! 请注意, apply需要一系列参数!

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. 所以调用console.log(args)必须是console.log.apply(console, [args]) ,而不是console.log.apply(console, args)表现相同 - 在你的例子中,数组中的每个项目都成为他自己的申请中的论点。

On the other hand you may also call console.log("foo", "bar", $("body")) 另一方面,您也可以调用console.log("foo", "bar", $("body"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM