是否可以从Javascript构造函数中调用函数,如下所示:
class Blockchain {
constructor(genesisBlock) {
this.blocks = []
addBlock(genesisBlock)
}
addBlock(block) {
if(this.blocks.length == 0) {
block.previousHash = "0000000000000000"
}
}
}
我得到以下内容:
addBlock is not defined
答案 0 :(得分:1)
是的,该方法是一种原型方法,需要从类的实例中调用(使用this
):
...
constructor(genesisBlock) {
this.blocks = []
this.addBlock(genesisBlock)
}
...
答案 1 :(得分:0)
为什么会出现此错误?
当您在构造函数中以下列方式调用addBlock函数时
constructor(genesisBlock) {
this.blocks = []
addBlock(genesisBlock)
}
It is looking for a global function called addBlock
。但它找不到任何内容。这就是为什么它会引发错误。您的addBlock是Blockchain类的一种方法.Blockchain类的实例将在实例化时继承它那么你需要用'this.addBlock'
constructor(genesisBlock) {
this.blocks = []
this.addBlock(genesisBlock)
}