Private Scope
- Private scope in JavaScript is the private members of a class or object that can only be accessed from within the class or object itself.
- To create a private variable or function, you can create using the # prefix. or using closures.
- Private scope can be useful for encapsulating data and behavior within a class or object. This can help to make your code more modular and reusable. It can also help to prevent errors by preventing consumers of your code from accidentally accessing or modifying private members.
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:
Javascript
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:
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.
Table of Content
- Private Scope
- Public Scope
- Protected Scope