Javascript - Class Private Properties


You can define methods and properties inside the constructor environment, capturing the variables in a closure, and ensure that these methods or properties would not be added to the prototype.

class Bus { 
        constructor(capacity) { 
                this.checkCapacity = function(value) { 
                        if (capacity >= value) { 
                                return true; 
                        return false; 
const jet = new Bus(200); 

console.log(jet.checkCapacity(100));    // true 

console.log(jet.capacity);              // undefined 

In the above example, the constructor environment stores the parameters and local variables, keeping class properties (capacity) private by making it inaccessible outside the constructor.

This keeps the private data completely safe and inaccessible from the class's instance.

Related Topics