Protected Scope
- Protected members are accessible only within the class itself and its subclasses. Protected methods can access properties by getting them from the WeakMap.
- Protected scope can be useful 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.
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:
Javascript
// 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:
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
Contact Us