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)
The first problem is your conditional:
should be
if you want to be explicit but you could just use a double equals instead of triple for a truthy answer that would include null or undefined:
The second problem, which makes it difficult to answer your question, is it’s totally unclear what
this.words
is, what you’re trying to get thelength
of, and why.If you’re trying to truncate the last letter of the variable
this.words
, for example, you would do:Only strings and arrays have a
length
, unless you’ve added a length to your own class’s prototype. Sothis.length
wouldn’t work unlessthis
is a string or an array or a class with a custom length method.