Home >>Javascript Tutorial >JavaScript Encapsulation
The JavaScript Encapsulation is basically a process of binding the data with the functions acting on the same data and allows to control and validate the data. There are two methods to achieve an encapsulation in the JavaScript: -
Using these following properties, encapsulation in JavaScript allows us to handle an object:
1. Here is an example of encapsulation that contains two data members with its 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("Sonu"); stud.setMarks(95); document.writeln(stud.getName()+" "+stud.getMarks()); </script>
Here is an example to validate the marks of a student:
<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("Sonu"); stud.setMarks(110);//alert() invokes document.writeln(stud.getName()+" "+stud.getMarks()); </script>
Here is an example where prototype based encapsulation is performed:
<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("Anand",95); document.writeln(stud.name+" "+stud.marks); </script>