[英]What's the difference between these two console.log overrides?
这会毫无问题地覆盖 console.log,这对我来说很有意义:
(function(c) {
console.log = function() {
c.apply(console, arguments);
}
})(console.log);
这个不起作用,我不明白为什么:
(function(c) {
console.log = function() {
c(arguments);
}
})(console.log);
当我调用 console.log 时,我只得到一个属性列表。
有什么不同?
我需要在第二个中使用 arguments 构建数组才能正常工作。
如果你像这样修改你的 function 它会起作用:
(function(c) { console.log = function() { // c(...arguments) also works c(...Object.values(arguments)); } })(console.log); console.log('hello world')
这是因为arguments
不是数组,而是类数组 object 。
function func(...args) { console.log(arguments); } func(1, 2, "hello", "world")
第二个代码示例没有像您预期的那样工作,因为您将arguments
object 原样传递给console.log
function 而在第一个代码示例中,由于使用了apply()
, arguments
中的属性object 作为单独的参数传递。 换句话说,数组或类似数组的 object散布到不同的 arguments 中。
第一个代码示例中的console.log
调用类似于以下内容:
console.log(arg1, arg2, arg3, ...)
而在第二个中,它是:
console.log({ 0: arg1, 1: arg2, 2: arg3, ... });
(function(c) {
console.log = function() {
const a = Array.from(arguments);
c(a.join(" "))
}
})(console.log);
这行得通。
arguments
是一个类对象,所以我们需要自己创建字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.