The private class members were introduced in ES2022 and use #
(hash) symbol prefix. It is possible to declare private fields, methods,
getters and setters as well as their static counterparts. The private members are only accessible from within the current class body and aren’t
inherited by subclasses. They also cannot be removed with delete
operator.
class MyClass {
#foo = 123;
bar(){
return this.#foo; // ok
}
}
const obj = new MyClass();
obj.#foo = 345; // error: #foo is not accessible outside of the class
Private class members that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring and should be
corrected or removed.
class MyClass {
#privateField1;
#privateField2; // Noncompliant: #privateField2 is unused
#privateMethod(){} // Noncompliant: #privateMethod is unused
publicMethod(){
return this.#privateField1;
}
}
To fix the code remove unused private member of the class.
class MyClass {
#privateField1;
publicMethod(){
return this.#privateField1;
}
}