我有一个集成到NodeJS中的C ++类,我想改变它的默认对象打印
示例:
var X = new mypkg.Thing() ;
console.log( X ) ; // prints the object in std way
console.log( X.toString() ) ; // prints Diddle aye day
console.log( '' + X ) ; // prints Diddle aye day
我在外部代码中定义了ToString,这有效。但我希望默认打印是相同的。
void WrappedThing::ToString( const v8::FunctionCallbackInfo<v8::Value>& args ) {
Isolate* isolate = args.GetIsolate();
args.GetReturnValue().Set( String::NewFromUtf8( isolate, "Diddle aye day") );
}
是否有&#39;检查&#39;覆盖的方法?
TIA
答案 0 :(得分:3)
node.js util
documentation中有一节。基本上,您可以在对象/类上公开inspect()
方法,或者通过对象上的特殊util.inspect.custom
符号设置函数。
以下是使用特殊符号的一个示例:
const util = require('util');
const obj = { foo: 'this will not show up in the inspect() output' };
obj[util.inspect.custom] = function(depth, options) {
return { bar: 'baz' };
};
// Prints: "{ bar: 'baz' }"
console.log(util.inspect(obj));