JavaScript Encapsulation

The JavaScript Encapsulation is a process of binding the data (i.e. variables) with the functions acting on that data. It allows us to control the data and validate it. To achieve an encapsulation in JavaScript: -

  • Use var keyword to make data members private.
  • Use setter methods to set the data and getter methods to get that data.

The encapsulation allows us to handle an object using the following properties:

Read/Write - Here, we use setter methods to write the data and getter methods read that data.

Read Only - In this case, we use getter methods only.

Write Only - In this case, we use setter methods only.

JavaScript Encapsulation Example

Let's see a simple example of encapsulation that contains two data members with its setter and getter methods.

Test it Now

Output:

John 80

JavaScript Encapsulation Example: Validate

In this example, we validate the marks of the student.

Test it Now

Output:

John undefined

JavaScript Encapsulation Example: Prototype-based approach

Here, we perform prototype-based encapsulation.

Test it Now

Output:

John 80
Next TopicJS Inheritance




Contact US

Email:[email protected]

JS Encapsulation
10/30