0

Is it possible to call a function from inside the Javascript constructor like this:

class Blockchain {

   constructor(genesisBlock) {

     this.blocks = []
     addBlock(genesisBlock)
   }

   addBlock(block) {

      if(this.blocks.length == 0) {
        block.previousHash = "0000000000000000"
      }
   }

}

I get the following:

addBlock is not defined
3
  • 2
    You have to call this.addBlock(genesisBlock) Commented Jan 16, 2018 at 16:30
  • Thanks KevBot. If you can post this as answer I can accept it :) Commented Jan 16, 2018 at 16:31
  • It's not just a function. It's a method. Commented Jan 16, 2018 at 16:58

2 Answers 2

1

Yes, the method is a prototypical method, and needs to be called from the instance of the class (by using this):

...
constructor(genesisBlock) {
    this.blocks = []
    this.addBlock(genesisBlock)
}
...
Sign up to request clarification or add additional context in comments.

Comments

0

Why you are getting this error?

When you are calling addBlock function inside the constructor in a following manner

   constructor(genesisBlock) {

     this.blocks = []
     addBlock(genesisBlock)
   }

It is looking for a global function called addBlock.But it can't find any.That's why it throws you an error.Your addBlock is a method of Blockchain class.Instances of Blockchain class will inherit it when instantiated.So you need to invoke it with 'this.addBlock'

 constructor(genesisBlock) {

     this.blocks = []
     this.addBlock(genesisBlock)
   }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.