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.
CodePudding user response:
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, ... });
CodePudding user response:
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")
CodePudding user response:
(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.