Javascript public and private class members

Javascript public and private class members

Modern JavaScript allows the usage of public and private class members, enhancing encapsulation within classes. Public class members can be accessed from instances of the class and from any derived classes, while private class members, which are prefixed with #, can only be accessed from within the class that defines them.

Here's a concise explanation followed by a code example demonstrating both public and private class members:

Example of Public and Private Class Members

javascriptclass Person {  
    // Public class member  
    name;  

    // Private class member  
    #age;  

    constructor(name, age) {  
        this.name = name; // Public member  
        this.#age = age;  // Private member  
    }  

    // Public method to access private member  
    getAge() {  
        return this.#age;  
    }  

    // Public method to display information  
    displayInfo() {  
        console.log(`Name: ${this.name}, Age: ${this.getAge()}`);  
    }  
}  

// Usage  
const person1 = new Person('Alice', 30);  
console.log(person1.name); // Output: Alice  
person1.displayInfo(); // Output: Name: Alice, Age: 30  

// Trying to access the private member directly will cause an error  
// console.log(person1.#age); // Uncaught SyntaxError: Private field '#age' must be declared in an enclosing class

Explanation

  1. Public Class Member: The name property is a public class member. It can be accessed directly from instances of the Person class.

  2. Private Class Member: The #age property is a private class member. It can only be accessed from within the Person class itself. Attempting to access it directly from an instance will result in a syntax error.

  3. Methods:

    • getAge(): This public method provides controlled access to the private #age property.

    • displayInfo(): Another public method that displays the person's name and age.

Summary

This example illustrates how public and private members work in modern JavaScript classes. Public members are accessible from outside the class, while private members help encapsulate data and can only be accessed through methods within the class. If you need further clarification or additional examples, feel free to ask!