繁体   English   中英

如何在Javascript中创建此类对象

[英]How to create this kind of Object in Javascript

我正在使用Node.js访问此hdPrivateKey,但它看起来像

 <hdPrivateKey...>

看起来不像普通的JS对象。

和console.log(address)看起来像

<Address: 19o9ghmkUrNVf4d57tQJuUBb2gT8sbzKyq, type: pubkeyhash, network: livenet>

console.log(Object.keys(address))看起来像

[ 'hashBuffer', 'network', 'type' ]

为什么内部密钥地址不同?

var bitcore = require('bitcore');
var HDPrivateKey = bitcore.HDPrivateKey;

var hdPrivateKey = new HDPrivateKey();
console.log(hdPrivateKey)
var retrieved = new HDPrivateKey(hdPrivateKey);
var derived = hdPrivateKey.derive("m/0");
var derivedByNumber = hdPrivateKey.derive(1).derive(2, true);
var derivedByArgument = hdPrivateKey.derive("m/1/2");

var address = derived.privateKey.toAddress();
console.log(Object.keys(address))
console.log(address)
// obtain HDPublicKey
var hdPublicKey = hdPrivateKey.hdPublicKey;

在Node.js中, console.log调用对象的功能inspect 在bitcore-lib中有此方法:

HDPrivateKey.prototype.inspect = function() {
  return '<HDPrivateKey: ' + this.xprivkey + '>';
};

而这种方法:

Address.prototype.inspect = function() {
  return '<Address: ' + this.toString() + ', type: ' + this.type + ', network: ' + this.network + '>';
};

您看到的行为是因为对象具有自己的inspect属性,该属性是一个函数并返回一个字符串。 console.log看到它正在记录一个对象时,它将查找该函数并在可用时使用它。 因此在Node上,这将记录<foo>

const o = {
    inspect() {
        return "<foo>";
    }
};
console.log(o);

这就是HDPrivateKey对象所做的一切。

如果要正确检查对象,请使用调试器。 或者,将utils.inspectcustomInspect设置为false

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM