在nodejs中,“检查”就像一个保留字
在调用console.log的node.js中,有一个名为inspect
的元素的对象,即使它仍然作为一个对象工作,它仍然undefined
。 我假设这是因为节点使用内部检测来打印出来的东西。
var thingTwo = { num: 1, func: function (x) { 2; }, inspect: function (x) { "hi"; }, }; console.log(thingTwo); // undefined
为了避免将来出现这个陷阱,还有其他一些能够打破标准function的词汇吗?
酷,这激起了我的好奇心,事实上,有一个没有logging的特征,一个对象可以提供自己的inspect
方法。 util.js中的相关代码:
function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (value && typeof value.inspect === 'function' && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { return String(value.inspect(recurseTimes)); }
也就是说,只有当inspect
存在时才是触发行为的函数。
如果一个对象具有inspect
属性并且它是一个函数,则console.log
输出它的返回值。
$ node > console.log({ inspect: function() { return 'hi'; } }); hi
如果我们看到源代码 ,我们会看到无法避免这种行为。 如果一个对象的inspect
是一个函数, console.log
将打印它的返回值。
请注意,在Node 0.6.x和之前, console.log
实际上并不打印undefined
,只是打印一个空行。 你只会看到undefined
如果你在REPL中这样做。