0% completed
Encapsulation is a fundamental concept in object-oriented programming that involves bundling the data (variables) and the methods (functions) that operate on the data into a single unit or class. It also restricts direct access to some of an object's components, which is a method of preventing accidental interference and misuse of the state.
Encapsulation is crucial for several reasons:
Let’s look at a simple example to understand why encapsulation is needed:
Explanation:
person
object stores name
and age
properties that are publicly accessible and modifiable without any restrictions.name
and age
of person
without any control, which might lead to inappropriate or erroneous data states.This lack of encapsulation can lead to problems such as:
In JavaScript, a closure is a function that remembers the environment in which it was created. This feature allows the function to access and manipulate variables that are external to that function, yet local to the scope in which it was defined, long after the outer function has executed.
Closures are a powerful way to achieve encapsulation because they allow you to hide the internal state of the object and expose only what is necessary via the function's return value.
This example creates a simple module to manage a user's age with validation, ensuring the age is only updated to valid values, and only retrievable through the module's methods.
Explanation:
Function Definition and Initialization:
createUser
is a function that encapsulates the _age
variable. This variable is initialized with the value provided (age
) and is hidden from the outside scope, making it private.getAge
and setAge
that form the public API for interacting with _age
.getAge Method:
_age
. It returns the current value of _age
, allowing it to be accessed but not directly modified from outside the createUser
function.setAge Method:
_age
. It accepts a newAge
parameter and includes validation to ensure the age is within an acceptable range (1 to 119 years old).newAge
is valid, _age
is updated.Using the Object's Methods:
getAge
method is called to retrieve and print this age.setAge
method is successfully used to update the age to 35 after validation, and the change is confirmed by calling getAge
again.With the introduction of ES6
, JavaScript classes became a standard way to achieve encapsulation. ES6 classes allow you to define methods and properties that are neatly encapsulated within class instances.
In addition, JavaScript has introduced syntax for private fields using a hash #
prefix, enhancing the encapsulation capabilities by restricting access to these properties from outside the class.
This example creates a Car
class with a private field to store the car's model and public getter and setter methods to access and update the model.
Explanation:
Private Field Initialization:
#model
is a private field in the Car
class, initialized through the constructor. This field is not accessible from outside the class, ensuring that the model data is protected and encapsulated.Public Getter Method:
getModel()
is a public method that allows external code to access the value of the #model
field. It simply returns the current value, providing read access to the private field.Public Setter Method:
setModel(newModel)
is a public method that allows external code to update the value of the #model
field. It assigns the new model to the private field, providing a controlled way to modify it.Using the Class:
Car
class, myCar
, is created with an initial model of "Toyota Corolla". The model is accessed using the getModel()
method and then updated using the setModel()
method to "Honda Civic". Subsequent calls to getModel()
confirm that the model was successfully updated.Getters and setters are methods used in object-oriented programming to provide controlled access to the properties of an object. In JavaScript, these accessors allow you to define custom logic for getting and setting a property, thus encapsulating and safeguarding the property's value from direct external manipulation.
This example creates a Temperature
class that uses getters and setters to manage a temperature property, ensuring that it can be accessed and modified in a controlled manner.
Explanation:
Class and Property Initialization:
Temperature
class is defined with a private property _celsius
, which is intended to hold the temperature in Celsius. This property is initialized via the constructor.Getter Method:
celsius
getter provides read access to the _celsius
property. When temp.celsius
is accessed, this getter is invoked to return the current temperature, thus providing a way to read the temperature without directly accessing the private variable.Setter Method:
celsius
setter allows controlled modification of the _celsius
property. When temp.celsius
is set to a new value, this setter is invoked, updating the temperature. This method provides a way to modify the temperature while encapsulating the logic that might involve validation or notification in more complex scenarios.Using the Class:
Temperature
object named temp
is created with an initial temperature of 22 degrees Celsius. The current temperature is accessed using the getter and displayed. Then, the temperature is updated to 25 degrees using the setter, and the new temperature is displayed, confirming that the update was successful......
.....
.....