Access Modifiers in JavaScript: A Comprehensive Guide

access_modifier

It is a versatile language that allows developers to create interactive web pages and perform various tasks on the client side. Access modifiers are crucial in object-oriented programming in JavaScript. They control the visibility and accessibility of properties and methods of a class.

Introduction to Access Modifiers

Access modifiers determine the accessibility of properties and methods of a class and, as such, define how an object can interact with the properties and methods of a class. JavaScript has four types of access modifiers: public, private, protected, and default. Each access modifier controls the visibility and accessibility of properties and methods of a class.

Public Access Modifier

By default, all properties and methods in JavaScript are public, which means that any object or function in the program can access them. To enable access to a property or method from any part of a program, a user can declare it explicitly as public.

class Car {
  constructor(make, model) {
    this.make = make;
    this.model = model;
  }

  drive() {
    console.log(`Driving ${this.make} ${this.model}`);
  }
}

const myCar = new Car('Honda', 'Civic');
myCar.drive(); // Output: Driving Honda Civic

In this example, make and model properties are public and can be accessed from anywhere in the program. The drive() method is also public and can be called by any object or function in the program.

Private Access Modifier

Declaring a property or method as private restricts their accessibility to only within the class, thus limiting access to class properties and methods. It means that accessing private properties and methods from outside the class is not possible.

class Person {
  #name;
  #age;

  constructor(name, age) {
    this.#name = name;
    this.#age = age;
  }

  getInfo() {
    console.log(`Name: ${this.#name}, Age: ${this.#age}`);
  }
}

const person1 = new Person('John', 25);
person1.getInfo(); // Output: Name: John, Age: 25
console.log(person1.#name); // Error: Private field '#name' must be declared in an enclosing class

In this example, name and age properties are declared as private using the # symbol. The getInfo() the method is public and can be accessed from anywhere in the program. However, name and age properties cannot be accessed from outside the class.

Protected Access Modifier

Declaring a property or method as protected permits access to the properties and methods of a class within the class and its subclasses. Therefore, any subclass that inherits from the class can access a protected property or method.

class Animal {
  constructor(name) {
    this._name = name;
  }

  eat() {
    console.log(`${this._name} is eating.`);
  }

  // Protected method
  _move() {
    console.log(`${this._name} is moving.`);
  }
}

class Cat extends Animal {
  constructor(name) {
    super(name);
  }

  // Override the base class method
  eat() {
    console.log(`${this._name} is eating fish.`);
  }

  // Use the protected method in the derived class
  move() {
    this._move();
  }
}

const cat = new Cat("Tom");
cat.eat(); // Output: Tom is eating fish.
cat.move(); // Output: Tom is moving.

In this example, we define a base Animal class with a public eat() method and a protected _move() method. The _move() the method can only be accessed within the class and its subclasses.

We then define a Cat a subclass that extends the Animal class and overrides the eat() method. In the move() method of Cat, we use the protected _move() the method from the base class to log a message to the console.

Finally, we create an instance of Cat and call it public eat() and move() methods, which use the protected method defined in the base class.

The Default Access Modifier

JavaScript uses the default access modifier when a property or method is not specified with an access modifier. By default, if no access modifier is specified, all properties and methods are public and accessible from anywhere in the program.

class Person {
  name;
  age;

  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  getInfo() {
    console.log(`Name: ${this.name}, Age: ${this.age}`);
  }
}

const person1 = new Person('John', 25);
person1.getInfo(); // Output: Name: John, Age: 25

In this example, name and age properties are declared without an access modifier, which means they are public by default. The getInfo() method is also public and can be accessed from anywhere in the program.

Access Modifiers in ES6 Classes

ES6 introduced a new syntax for creating classes in JavaScript. One can use symbols to implement access modifiers in ES6 classes. Private properties and methods are denoted by the # symbol, while protected properties and methods are denoted by the _ symbol.

class Person {
  #name;
  _age;

  constructor(name, age) {
    this.#name = name;
    this._age = age;
  }

  getInfo() {
    console.log(`Name: ${this.#name}, Age: ${this._age}`);
  }
}

const person1 = new Person('John', 25);
person1.getInfo(); // Output: Name: John, Age: 25
console.log(person1.#name); // Error: Private field '#name' must be declared in an enclosing class

In this example, the name property is declared as private using the # symbol, while the age property is declared as protected using the _ symbol.

Importance of Access Modifiers in Object-Oriented Programming

Access modifiers are an essential aspect of object-oriented programming. They ensure the correct use of a class’s properties and methods, as well as prevent accidental misuse. By controlling the visibility and accessibility of properties and methods, access modifiers help to encapsulate the internal workings of a class and promote modularity.

Best Practices for Using Access Modifiers

  • Use the public access modifier for properties and methods that need to be accessed from anywhere in the program.
  • Use the private access modifier for properties and methods that should only be accessed within the class.
  • Use the protected access modifier for properties and methods that should be accessible within the class and its subclasses.
  • Avoid using the default access modifier, as it can lead to unexpected behavior and make it harder to maintain your code.
  • Use symbols to implement access modifiers in ES6 classes.

Conclusion

Access modifiers are an essential aspect of object-oriented programming in JavaScript. Access modifiers control the properties and methods of a class, managing their visibility and accessibility to ensure proper usage of the class.

Follow Us
https://www.linkedin.com/company/scribblers-den/

https://www.facebook.com/scribblersden.blogs

Read More
https://scribblersden.com/math-objects-in-javascript/

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *