Explanation, "this" syntax JavaScript

So I was making a node app that had a conditional statement in the class constructor, if this then variable is equal to that, else variable equal to that. However, when I initialize that variable I want to change depending on the boolean statement with "this" syntax it gives me an error in the console. Why does this happen? And how can I initialize that variable if I can’t initialize it more than once with "this" syntax in JS?

Update:

I was given How does 'this' work in JavaScript? to see if this helps, and it has nothing to do with what I asked. To be more specific, it’s like why can I do this var test; if(true){var test = 1}else{var test = 0} and not this if(true){this.test = 1}else{this.test = 0} and be able to use the variable all throughout my app.

code:

class Wallet {
  constructor(secret) {
      //ADDED SECRET PARAMETER
    this.secret = secret;
    
    this.balance = STARTING_BALANCE;

    if(this.secret === null || undefined)
    {
        this.keyPair = ec.genKeyPair();
    
        this.publicKey = this.keyPair.getPublic().encode('hex');
    }
    else
    {
        this.keyPair = ec.keyFromPrivate(this.secret);
        
        this.storeKeys = this.keyPair.toString('hex');
        
        //fs.writeFileSync('../secret.json');
        this.publicKey = this.keyPair.getPublic().encode('hex');
    }

    
  }

console error:

/home/main/public_html/Cypher-Network/node_modules/bn.js/lib/bn.js:622
    var w = this.words[this.length - 1];
                      ^

TypeError: Cannot read property '-1' of null
    at BN.bitLength (/home/main/public_html/Cypher-Network/node_modules/bn.js/lib/bn.js:622:23)
    at Point._hasDoubles (/home/main/public_html/Cypher-Network/node_modules/elliptic/lib/elliptic/curve/base.js:332:48)
    at Point.mul (/home/main/public_html/Cypher-Network/node_modules/elliptic/lib/elliptic/curve/short.js:426:17)
    at KeyPair.getPublic (/home/main/public_html/Cypher-Network/node_modules/elliptic/lib/elliptic/ec/key.js:61:26)
    at new Wallet (/home/main/public_html/Cypher-Network/src/wallet/index.js:26:39)
    at Object.<anonymous> (/home/main/public_html/Cypher-Network/src/blockchain/dataBlock.js:4:16)
    at Module._compile (internal/modules/cjs/loader.js:1158:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
    at Module.load (internal/modules/cjs/loader.js:1002:32)
    at Function.Module._load (internal/modules/cjs/loader.js:901:14)

27 thoughts on “Explanation, "this" syntax JavaScript”

  1. 770904 629172hi!,I like your writing so considerably! share we communicate a lot more about your article on AOL? I call for an expert on this area to solve my dilemma. Maybe thats you! Searching forward to see you. 116517

    Reply

Leave a Comment