Version: v6.3.1
Platform: any
Code...
console.log({
inspect: function () {
return 123;
},
});
...will print:
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.
But how about starting favouring
toStringoverinspect?
I am not sure that鈥檚 a good idea, both because inspect has been around for a long time and because they have different semantics; toString() is used when something machine-readable is needed, whereas .inspect() is for humans and can even return non-strings.
A Symbol property that would take precedence over .inspect might be a better idea to work around this because that鈥檚 guaranteed not to conflict with anything.
+1.. was just thinking the same thing. Having a util.Inspect symbol such that {[util.Inspect]:function() {}} is favored over {inspect:function(){}} would be good in theory. In practice, however, it may be quite difficult, and take some time, to get implementers to update to the new Symbol. It's not out of the question tho and would be a good best practice to encourage.
In 6.4.0, you should be able to disable this behaviour through:
util.inspect.defaultOptions.customInspect = false
See #8174 for a symbol-based approach that would make it possible to ignore the inspect property of an object.
We know a solution: use symbols but it cannot respect backward compatibility.
But the worst problem is communication on nodeJS reserved keywords that should be on the first doc page to avoid wastes of time while debugging.
Then, future solution should be available on newest versions to start using a right syntax.
Most helpful comment
We know a solution: use symbols but it cannot respect backward compatibility.
But the worst problem is communication on nodeJS reserved keywords that should be on the first doc page to avoid wastes of time while debugging.
Then, future solution should be available on newest versions to start using a right syntax.