Blockchain JS运行报TypeError:无法读取undefined的length属性
问题根因
报错和JavaScript版本迭代、语法兼容无关,是代码中两处笔误导致:
Blockchain类构造函数名拼写错误:JavaScript类构造函数的固定命名为constructor,代码中错写为contstructor(字母s、t顺序颠倒),实例化Blockchain时初始化逻辑未执行,this.chain属性从未被赋值。getLatestBlock方法缺少返回语句:方法体内仅编写了取链尾区块的表达式,未通过return返回结果,方法默认返回undefined,后续访问.hash属性时相当于读取undefined的属性,直接触发运行时错误。
修复后完整代码
const SHA256 = require("crypto-js/sha256"); class Block { constructor(index, timestamp, data, previousHash = "") { this.index = index; this.timestamp = timestamp; this.data = data; this.previousHash = previousHash; this.hash = this.calculateHash(); } calculateHash() { return SHA256( this.index + this.previousHash + this.timestamp + JSON.stringify(this.data) ).toString(); } } class Blockchain { constructor() { this.chain = [this.createGenesisBlock()]; } createGenesisBlock() { return new Block(0, "01/01/2017", "Genesis block", "0"); } getLatestBlock() { return this.chain[this.chain.length - 1]; } addBlock(newBlock) { newBlock.previousHash = this.getLatestBlock().hash; newBlock.hash = newBlock.calculateHash(); this.chain.push(newBlock); } } let savejeeCoin = new Blockchain(); savejeeCoin.addBlock(new Block(1, "10/07/2017", { amount: 4 })); savejeeCoin.addBlock(new Block(2, "12/07/2017", { amount: 10 })); console.log(JSON.stringify(savejeeCoin, null, 4));
内容的提问来源于stack exchange,提问作者Sheroze Mohammed
相关产品推荐
相关产品推荐

