Encapsulation
Last updated
Last updated
Encapsulation in JavaScript is a concept that refers to bundling the data (variables) and methods (functions) that operate on the data into a single unit, typically known as a class.
It allows you to control access to the data, ensuring that it's accessed and modified only through the defined methods.
This helps in keeping the internal state of an object consistent and prevents external code from directly manipulating it, thus promoting data integrity and security.
In this example:
Car
class encapsulates the properties make
, model
, and year
, along with the _mileage
property which is intended to be private (though JavaScript doesn't strictly enforce this).
Methods like getMileage()
and drive(distance)
provide controlled access to the _mileage
property, allowing its retrieval and modification in a controlled manner.
While JavaScript doesn't have strict visibility modifiers like some other languages, developers typically use naming conventions (like prefixing private members with an underscore) to indicate which properties or methods are intended to be private. However, these can still be accessed and modified directly, which is why encapsulation in JavaScript is more about convention and intention rather than strict enforcement.