JavaScript encapsulation is the technique of associating data (such as variables) with the functions that operate on that data. This approach enables us to regulate the data and perform validation. To implement encapsulation in JavaScript:
- Utilize the var keyword to designate data members as private.
- Employ setter methods for assigning values to the data and getter methods for retrieving that data.
Encapsulation enables us to manage an object through the subsequent attributes:
In this context, setter methods are utilized to input or modify the data, while getter methods are employed to retrieve or access that data.
Read-Only - In this scenario, we exclusively utilize getter methods.
In this scenario, we exclusively utilize setter methods.
JavaScript Encapsulation Example
Let’s examine a straightforward illustration of encapsulation that includes two data members along with their respective setter and getter methods.
<script>
class Student
{
constructor()
{
var name;
var marks;
}
getName()
{
return this.name;
}
setName(name)
{
this.name=name;
}
getMarks()
{
return this.marks;
}
setMarks(marks)
{
this.marks=marks;
}
}
var stud=new Student();
stud.setName("John");
stud.setMarks(80);
document.writeln(stud.getName()+" "+stud.getMarks());
</script>
Output:
John 80
JavaScript Encapsulation Example: Validate
In this instance, we assess the student's scores.
<script>
class Student
{
constructor()
{
var name;
var marks;
}
getName()
{
return this.name;
}
setName(name)
{
this.name=name;
}
getMarks()
{
return this.marks;
}
setMarks(marks)
{
if(marks<0||marks>100)
{
alert("Invalid Marks");
}
else
{
this.marks=marks;
}
}
}
var stud=new Student();
stud.setName("John");
stud.setMarks(110);//alert() invokes
document.writeln(stud.getName()+" "+stud.getMarks());
</script>
Output:
John undefined
JavaScript Encapsulation Example: Prototype-based approach
Here, we perform prototype-based encapsulation.
<script>
function Student(name,marks)
{
var s_name=name;
var s_marks=marks;
Object.defineProperty(this,"name",{
get:function()
{
return s_name;
},
set:function(s_name)
{
this.s_name=s_name;
}
});
Object.defineProperty(this,"marks",{
get:function()
{
return s_marks;
},
set:function(s_marks)
{
this.s_marks=s_marks;
}
});
}
var stud=new Student("John",80);
document.writeln(stud.name+" "+stud.marks);
</script>
Output:
John 80