// ES2022
class InstPrivateClass {
#privateField1 = 'private field 1'; // (A)
#privateField2; // (B) required!
constructor(value) {
this.#privateField2 = value; // (C)
}
/**
* Private fields are not accessible outside the class body.
*/
checkPrivateValues() {
console.log(this.#privateField1); // output -> 'private field 1'
console.log(this.#privateField2); // output -> 'constructor argument'
}
}
const inst = new InstPrivateClass('constructor argument');
inst.checkPrivateValues();
console.log("inst", Object.keys(inst).length === 0) //output -> inst, true
// ES2022
class InstPrivateClass {
#privateField1 = 'private field 1'; // (A)
#privateField2; // (B) required!
static #staticPrivateField = 'hello';
constructor(value) {
this.#privateField2 = value; // (C)
}
/**
* Private fields are not accessible outside the class body.
*/
checkPrivateValues() {
console.log(this.#privateField1); // output -> 'private field 1'
console.log(this.#privateField2); // output -> 'constructor argument'
}
static #twice() {
return this.#staticPrivateField + " " + this.#staticPrivateField;
}
static getResultTwice() {
return this.#twice()
}
}
const inst = new InstPrivateClass('constructor argument');
inst.checkPrivateValues();
console.log("inst", Object.keys(inst).length === 0) //output -> "inst", true
console.log(InstPrivateClass.getResultTwice()); // output -> "hello hello"
// ES2022
class MyClass {
#privateMethod() {}
static check() {
const inst = new MyClass();
console.log(#privateMethod in inst) // output-> true
console.log(#privateMethod in MyClass.prototype) // output-> false
console.log(#privateMethod in MyClass) // output-> false
}
}
MyClass.check();