在nodejs'inspect'表现得像个保留字

In nodejs 'inspect' acts like a reserved word

本文关键字:保留字 inspect nodejs      更新时间:2024-02-25

在node.js中,对具有inspect元素的对象调用console.log会打印undefined,即使它仍然可以作为对象工作。我认为这是因为节点在内部使用inspect来打印内容。

var thingTwo = {
  num: 1,
  func: function (x) { 2; },
  inspect: function (x) { "hi"; },
};
console.log(thingTwo);  // undefined

为了避免将来出现这种陷阱,是否有一系列其他单词会破坏标准功能?

很酷,这激发了我的好奇心,事实上,有一个未记录的特性,对象可以提供自己的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,它只是打印一个空行。只有在REPL中执行此操作时,才会看到undefined