CodesJava

Easy learning with example program codes

JavaScript Encapsulation

OOPs restrict direct access to its methods and variables by encapsulating the code and data together. In javascript, the data binds with the functions acting on that data in the process of achieving encapsulation in order to control the data and validate it.

There are two ways of encapsulation in Javascript:

  • Making data members private using var keyword.
  • Set the data using setter methods and get that data using getter methods.

We can manage read and write access of object’s properties by using encapsulation.

  • Read Only Access : If we declare getter methods only then it facilitates the read only access.
  • Write Only Access : If we declare setter methods only then it facilitates the write only access.
  • Read & Write Access : If we declare both getter and setter methods then it facilitates both read and write access.

Example:

<!DOCTYPE html>
<html>
<body>
 
<script>
class Employee
  {
    constructor()
    {
       var name;
       var rating;
    }
        getName()
        {
          return this.name;
        }
      setName(name)
      {
        this.name=name;
      }
 
      getRating()
      {
        return this.rating;
      }
    setRating(rating)
    {
          this.rating=rating;
    }
    }
    var emp=new Employee();
     emp.setName("Naren");
     emp.setRating(9);
     document.writeln(emp.getName()+" "+emp.getRating());
</script>
 
</body>
</html>

Output

Naren 9

JavaScript encapsulation example using Prototype:

<!DOCTYPE html>
<html>
<body>
 
<script>
function Employee(id,name)
{
  var eId=id;
  var ename=name;
  Object.defineProperty(this,"name",{
    get:function()
    {
      return ename;
    },
  set:function(ename)
  {
    this.ename=ename;
  }
 
});
 
    Object.defineProperty(this,"id",{
    get:function()
    {
      return eId;
    },
  set:function(eId)
  {
    this.eId=eId;
  }
 
});
 
}
  var emp=new Employee(101, "Pooja");
  document.writeln(emp.id+" "+emp.name);
</script>
 
</body>
</html>

Output

101 Pooja
Please follow and like us:
error








Copyright © 2019 CodesJava DMCA.com Protection Status