javascript - 类构造函数的未定义返回——JavaScript
问题描述
我有一个文件是 block.js:
class Block{
constructor(timeStamp, lastBlockHash, thisBlockData, thisBlockHash){
this.timeStamp = timeStamp;
this.lastBlockHash = lastBlockHash;
this.thisBlockData = thisBlockData;
this.thisBlockHash = thisBlockHash;
}
static genesis(){
return new this(Date.now(), "---", "genesis block", "hash of the genesis");
}
}
我有另一个文件 blockchain.js 我有以下内容:
const Block = require('./block');
class BlockChain{
constructor() {
this.chain = BlockInstance.genesis();
}
}
我有一个我正在做的测试文件:
const Block = require("./block.js");
const BlockChain = require("./blockchain.js");
console.log(BlockChain.chain);
我在打印输出中得到了一个“未定义”的对象..这真的让我发疯了,因为我已经花了 4 个多小时在它上面..如果有人能为我解开这个谜团,那么请给我一杯啤酒..
干杯,炼金术士
解决方案
你应该实例化类
const Block = require("./block.js");
const BlockChain = require("./blockchain.js");
let block = new Block(...);
let blockChain = new BlockChain();
console.log(blockChain.chain);
有关使用 JS 构建区块链的示例,您可能需要关注类似This one from medium的网站
该genesis()
方法更适合成为链的一部分,因为这是链的属性,而不是不同类型的块。
推荐阅读
- r - 使用 r 中的子函数来检索连字符之间的特定文本
- arduino - 如何为 Arduino 代码提供条件编译?
- python - 无法存储格式为 %Y.%m.%d 的数据框日期列
- django-authentication - 如何以账号等整数作为用户名认证用户
- java - MX Player 打开而不是通过 Intent 播放视频
- python - 如何根据行的第一个字符向上移动字符串?
- html - Disappeared table header row after using "stacked" property
- android - 如何将应用程序中的图像从图库添加到 android 的 recyclerview 中?
- mysql - Sequelize associate 为一个模型创建 userId 和 user_id,但不为另一个模型创建 userId 和 user_id
- java - 无法处理我的导航菜单项的点击事件