简体   繁体   English

这两个 console.log 覆盖有什么区别?

[英]What's the difference between these two console.log overrides?

This overrides console.log without issue and it makes sense to me:这会毫无问题地覆盖 console.log,这对我来说很有意义:

(function(c) {
  console.log = function() {
    c.apply(console, arguments);
  }
})(console.log);

This one does not work and I don't understand why:这个不起作用,我不明白为什么:

(function(c) {
  console.log = function() {
    c(arguments);
  }
})(console.log);

I just get a list of properties when I call console.log.当我调用 console.log 时,我只得到一个属性列表。

What's the difference?有什么不同?

I need to build the array with arguments in the second one for it to work.我需要在第二个中使用 arguments 构建数组才能正常工作。

It works if you modify your function like this:如果你像这样修改你的 function 它会起作用:

 (function(c) { console.log = function() { // c(...arguments) also works c(...Object.values(arguments)); } })(console.log); console.log('hello world')

This is because arguments is not an array, but an array-like object .这是因为arguments不是数组,而是类数组 object

 function func(...args) { console.log(arguments); } func(1, 2, "hello", "world")

The second code example doesn't works as you expect it to because you are passing the arguments object as it is to the console.log function whereas in the first code example, due to the usage of apply() , the properties in the arguments object are passed as a separate argument.第二个代码示例没有像您预期的那样工作,因为您将arguments object 原样传递给console.log function 而在第一个代码示例中,由于使用了apply()arguments中的属性object 作为单独的参数传递。 In other words, array or an array-like object is spread in to distinct arguments.换句话说,数组或类似数组的 object散布到不同的 arguments 中。

The console.log call in the first code example is similar to the following:第一个代码示例中的console.log调用类似于以下内容:

console.log(arg1, arg2, arg3, ...)

whereas in the second one, it is as:而在第二个中,它是:

console.log({ 0: arg1, 1: arg2, 2: arg3, ... });
(function(c) {
  console.log = function() {
    const a = Array.from(arguments);
    c(a.join(" "))
  }
})(console.log);

This works.这行得通。

arguments is an object-like so we need to create the string ourselves. arguments是一个类对象,所以我们需要自己创建字符串。

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

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