简体   繁体   中英

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

This overrides console.log without issue and it makes sense to me:

(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.

What's the difference?

I need to build the array with arguments in the second one for it to work.

It works if you modify your function like this:

 (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 .

 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. In other words, array or an array-like object is spread in to distinct arguments.

The console.log call in the first code example is similar to the following:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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