Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 15, 2023 01:15 am GMT

Encapsulation Explained using JavaScript

Encapsulation is one of the fundamental principles of object-oriented programming (OOP) that refers to the concept of binding the data (member variable) and the methods that operate on the data (member functions) within a single unit called a class.

Encapsulation enables programmers to hide the implementation details of one object from other objects and restrict direct access to the internal state of an object.

Encapsulation provides several benefits, such as:

  • improving the maintainability of the code -- making it easier to modify and extend the class's functionality.

  • Enhancing the security of the data by preventing unauthorized access.

  • It also allows the programmer to use the class's interface without knowing the implementation details, which makes it easier to use and understand.

let look at an example of encapsulation in JavaScript:

function createCounter() {  let count = 0;  function increment() {    count++;    console.log(count);  }  return increment;}const counter = createCounter();counter(); // Output: 1counter(); // Output: 2counter(); // Output: 3

In this example, we have a createCounter function that returns an increment function. The increment function has access to the count variable through a closure, but the count variable is not accessible from outside the function. The only way to modify the count variable is by calling the increment function, which increments the count and logs it to the console.
This is an example of encapsulation because the count variable is hidden from the outside world and can only be accessed through the increment function, which provides a well-defined interface for accessing and modifying the count.

In addition to using closures, another way to achieve encapsulation in JavaScript is by using setters and getters. Setters and getters are methods that allow us to control how properties are set and retrieved from an object.

Here's an example of encapsulation using setters and getters:

class Person {  constructor(name, age) {    this._name = name;    this._age = age;  }  get name() {    return this._name;  }  set name(newName) {    if (typeof newName === "string") {      this._name = newName;    } else {      throw new Error("Name must be a string");    }  }  get age() {    return this._age;  }  set age(newAge) {    if (typeof newAge === "number" && newAge > 0) {      this._age = newAge;    } else {      throw new Error("Age must be a positive number");    }  }}const person = new Person("John Doe", 30);console.log(person.name); // Output: John Doeconsole.log(person.age); // Output: 30person.name = "Jane Doe";person.age = 25;console.log(person.name); // Output: Jane Doeconsole.log(person.age); // Output: 25person.name = 123; // Throws an error: Name must be a stringperson.age = -1; // Throws an error: Age must be a positive number

In this example, we have a Person class with name and age properties that are encapsulated using setters andgetters. The getters allow us to retrieve the values of these properties, while the setters allow us to control how they are set.

For instance, the name setter checks whether the new value is a string before setting the _name property, while the age setter checks whether the new value is a positive number. This allows us to enforce certain constraints on the values of these properties and ensure that they are always valid.

By encapsulating thename and age properties using setters and getters, we can hide their internal implementation and control how they are accessed and modified from outside the class. This helps to maintain the integrity of the object and prevent any unexpected side-effects that could result from direct manipulation of its properties.

In Summary, In encapsulation can be achieved through the use of closures and modules, as well as using setters and getters to control how properties are set and retrieved from an object. it also helps to improve the quality and maintainability of software systems.


Original Link: https://dev.to/akpevwe11/encapsulation-explained-using-javascript-21hl

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To