With the recent addition to JavaScript with ES2022, classes can now have private methods along with private fields which are accessible only through class object.
To define a private method we prefix the method name with #
sign.
You can define private method for instance, static and getters/setters methods in a class.
// Syntax for defining a private method
class SamplePrivateMethod {
#privateMethod() {
// function definition to perform any action.
}
}
Rules for defining private methods
#
Symbol is used to define private method.- Private methods can be accessed inside a class only not from subclass (extended class).
- To access private method you can use
this
keyword as well as class name.
class Car {
#speed;
get #getCarSpeed() {
return this.#speed;
}
// using this keyword
set #setCarSpeedUsingThisKeyword(value) {
this.#speed = value;
}
// using class name
set #setCarSpeedUsingClassName (value) {
Car.#speed = value;
}
}
Example: Instance private method
class StreetAddress {
// private fields
#lineOne;
#lineTwo;
// class fields are accessed using this keyword.
constructor(lineOne, lineTwo) {
this.#lineOne = lineOne;
this.#lineTwo = lineTwo;
}
// defined function that can be accessed outside class.
getFormattedAddress() {
return this.#lineOne() + ' , ' + this.#lineTwo();
}
// private functions for processing of data accessible only inside class.
#getLineOne() {
return `${this.#lineOne}`;
}
#getLineTwo() {
return `${this.#lineTwo}`;
}
}
let formattedAddress = new StreetAddress('123 Sample Street', 'Sample City');
console.log(formattedAddress.getFormattedAddress());
// output : 123 Sample Street , Sample City
Example: Instance private method & Static private method
class StreetAddress {
// private fields
#lineOne;
#lineTwo;
// class fields can be accessed using both,
// this keyword & class name.
constructor(lineOne, lineTwo) {
this.#lineOne = this.#validateAddress(lineOne);
this.#lineTwo = StreetAddress .#validateAddress(lineTwo);
}
static #validateAddress(addressLine) {
if (typeof addressLine === 'string') {
let str = addressLine.trim();
if (str.length >= 3) {
return str;
}
}
throw 'Address line cannot be left blank.';
}
// defined function that can be accessed outside class.
getFormattedAddress() {
return this.#lineOne() + ' , ' + this.#lineTwo();
}
// private functions for processing of data accessible only inside class.
#getLineOne() {
return `${this.#lineOne}`;
}
#getLineTwo() {
return `${this.#lineTwo}`;
}
}
let formattedAddress = new StreetAddress('123 Sample Street', 'Sample City');
console.log(formattedAddress.getFormattedAddress());
// output : 123 Sample Street , Sample City