首页 > 解决方案 > 类构造函数的未定义返回——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 个多小时在它上面..如果有人能为我解开这个谜团,那么请给我一杯啤酒..

干杯,炼金术士

标签: javascriptnode.jsexpress

解决方案


你应该实例化类

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()方法更适合成为链的一部分,因为这是链的属性,而不是不同类型的块。


推荐阅读