【问题标题】:What does a [Function] (wrapped in square brackets) mean when inside of a javascript object?[Function](用方括号括起来)在 javascript 对象中是什么意思?
【发布时间】:2015-09-08 16:32:42
【问题描述】:

在各种函数上运行 console.log 时,我会在 value 部分中找到值为 [Function: someFunctionName] 的对象的属性。这是什么意思?我希望能够查看函数的实际代码。当我看到这种语法时,我对实际记录的内容感到困惑。

这是一个例子:Logging mongoose.Schema 有以下输出

{ [Function: Schema]
  reserved: 
   { _posts: 1,
     _pres: 1,
     validate: 1,
     toObject: 1,
     set: 1,
     schema: 1,
     save: 1,
     modelName: 1,
     get: 1,
     isNew: 1,
     isModified: 1,
     init: 1,
     errors: 1,
     db: 1,
     collection: 1,
     once: 1,
     on: 1,
     emit: 1 },
  interpretAsType: [Function],
  Types: 
   { String: { [Function: SchemaString] schemaName: 'String' },
     Number: { [Function: SchemaNumber] schemaName: 'Number' },
     Boolean: { [Function: SchemaBoolean] schemaName: 'Boolean', '$conditionalHandlers': [Object] },
     DocumentArray: { [Function: DocumentArray] schemaName: 'DocumentArray' },
     Array: { [Function: SchemaArray] schemaName: 'Array' },
     Buffer: { [Function: SchemaBuffer] schemaName: 'Buffer' },
     Date: { [Function: SchemaDate] schemaName: 'Date' },
     ObjectId: { [Function: ObjectId] schemaName: 'ObjectId' },
     Mixed: { [Function: Mixed] schemaName: 'Mixed' },
     Oid: { [Function: ObjectId] schemaName: 'ObjectId' },
     Object: { [Function: Mixed] schemaName: 'Mixed' },
     Bool: { [Function: SchemaBoolean] schemaName: 'Boolean', '$conditionalHandlers': [Object] } },
  ObjectId: { [Function: ObjectId] schemaName: 'ObjectId' } }

在几行中,存在[Function] 语法,后跟似乎是第二个属性(即使没有中间逗号),如下所示:ObjectId: { [Function: ObjectId] schemaName: 'ObjectId' } }

那么[Function] 实际表示的那些属性是什么?

【问题讨论】:

  • 你究竟是如何“记录”这个值的?
  • 我 console.log 用于节点上 V8 引擎中的值

标签: javascript node.js javascript-objects


【解决方案1】:

我可以使用以下设置复制输出:

> function bar() {}
> bar.baz = 42;
> console.log({foo: bar});
{ foo: { [Function: bar] baz: 42 } }

所以

ObjectId: { [Function: ObjectId] schemaName: 'ObjectId' } }

表示ObjectId 是对象的属性。该值是具有 name ObjectId 的 function。该函数有一个属性schemaName,其值为'ObjectId'


所以输出看起来有点奇怪,因为该函数具有自定义属性。这是相当罕见的。这将是没有自定义属性的输出:

{ foo: [Function: bar] }

【讨论】:

  • 在 console.log 行上,foo 未定义。我相信应该是bar
  • 不确定你的意思。 {foo: bar} 是一个对象字面量。 foo 是属性名称。
  • {foo: foo} foo 未定义
  • 谢谢。关于如何实际查看函数本身的任何想法?我可以在不使用 bar.toString() 之类的格式化的情况下做到这一点
  • 如果你在节点上,你可能会调用 toString() 方法,但将它传递给一些漂亮的打印机库。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-30
  • 2022-11-30
  • 2012-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多