Open In App

Public, Private, and Protected Scope in JavaScript

In this article, we will see the fundamentals of public, private, and protected scopes in JavaScript. We’ll explore how to create these scopes, their practical applications, and the conventions used to simulate access control.

Scopes

Private Scope:

When to use Private Scope?

Use private scope for variables and functions that should only be accessible from within the class or object in which they are defined. For example, you might use private scope for the internal state of a class or object, or for implementation details of a method or function.



Example:




let Employee = (function () {
 
    // Private variable
    let empName = '';
 
    return class {
        constructor(name) {
            empName = name;
        }
 
        // Private method
        getPrivateName() {
            return empName;
        }
    }
 
})();
 
const employee = new Employee('Aryan');
 
// Can access private method
console.log(employee.getPrivateName());
 
// Cannot access private variable
console.log(employee.privateName);

Output:

private

Public Scope:

When to use Public Scope?

Use public scope for variables and functions that need to be accessible from anywhere in your code. For example, you might use public scope for global variables or functions that are used by multiple parts of your code.

Example:




// Public variable
let empName = 'Aryan';
 
class Employee {
    constructor() {
         
        // Public method
        this.getName = function () {
            return empName;
        }
    }
}
 
const employee = new Employee();
 
// Can access public method
console.log(employee.getName());

Output:

public

Protected Scope:

When to use Protected Scope?

Use protected scope for variables and functions that need to be accessible from within the class in which they are defined, and from any classes that inherit from that class. For example, you might use protected scope for variables and functions that are shared by all subclasses of a particular class.

Example:




// WeakMap to store protected properties
const protectedMap = new WeakMap();
 
class Person {
    constructor(name) {
 
        // Add property to WeakMap
        protectedMap.set(this, {
            name
        });
    }
 
    // Protected method
    getName() {
 
        // Access property via WeakMap
        return protectedMap.get(this).name;
    }
}
 
// Extend Person class
class Employee extends Person {
    constructor(name, title) {
        super(name);
 
        // Add additional property
        protectedMap.get(this).title = title;
    }
 
    getTitle() {
        return protectedMap.get(this).title;
    }
}
 
const emp = new Employee('Aryan', 'Manager');
 
console.log(emp.getName());
console.log(emp.getTitle());
 
// Doesn't work - protected
console.log(emp.name);

Output:

protected


Article Tags :