Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This is a test script to test the new "private fields" in classes. (May not work now due to incomplete implementation)
class PrivateNameTest{
#lucky_number; //This hopefully can be tried without the semicolon once the proposal is implemented.
constructor(){
this.#lucky_number = 42;
}
guessLuckyNumber(guessedNumber){return guessedNumber===this.#lucky_number;}
}
class PrivateDefTest{
#arePrivateVariablesAwesome = true;
constructor(){}
amIAwesome(){return this.#arePrivateVariablesAwesome;}
}
class PrivateMethodTest{
#RNG(max,min){
//if methods doesn't work but variables do, put "=function" in between the "RNG" and "()"
return Math.ceil( ( Math.random() * (max - min + 1) ) + (min - 1) );
}
#diceSides;
constructor(sideCount){
this.#diceSides = sideCount;
}
roll(){
return this.#RNG(this.#diceSides,1);
}
}
//If those won't give syntax errors, code below will run.
console.log((new PrivateNameTest()).guessLuckyNumber(3)); //false
console.log((new PrivateDefTest()).amIAwesome()); //true
console.log((new PrivateMethodTest(6)).roll()); //some number between 1-6
@fbarda

This comment has been minimized.

Copy link
Owner Author

@fbarda fbarda commented Aug 12, 2020

Turns out, you can't extend on private fields.

Let me fix that.

@fbarda

This comment has been minimized.

Copy link
Owner Author

@fbarda fbarda commented Aug 16, 2020

The proposal if you want to know more.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment