Public Scope
- The Variables and methods declared directly on a class or outside any block are considered public in JavaScript.
- By default, everything declared in JavaScript is public. There is no concept of private/protected by default.
- Public scope can be useful for variables and functions that need to be used by multiple parts of your code. For example, you might use public scope for global variables or functions that are used by all pages of your website.
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:
Javascript
// 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, 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