Closed
Description
Version: v6.3.1
Platform: any
Code...
console.log({
inspect: function () {
return 123;
},
});
...will print:
123
That's because console.log
is using under the hood util.inspect which apparently will call inspect
method on given object if finds one.
This behaviour is very suprising and looks like a bug to someone who didn't read that particular doc. As a matter of fact I also maintain library which has inspect
method as part of its API. So doing console.log(myLib) will lead to obscure error.
Solution?
Both APIs console and util have status stable so I believe there is no way to alter this behaviour.
But how about starting favouring toString
over inspect
?
So this code...
console.log({
inspect: function () {
return 123;
},
toString: function () {
return 'foo';
},
});
...will print foo
instead of 123
.
Then at least I'll be able to define toString
method and avoid nasty error for the users of my library.