Sunday, September 16, 2012

Encapsulation in JavaScript

Public Memebers -
 Lets see the following example -
 function Person(){
    this.name = 'name1';  
}

var p = new Person();
alert(p.name);

Private memeber -
Lets see the following example -
function Person(){
    var name = 'name1';
    this.getname = function(){
        return name;
    }
}
var p = new Person();
alert(p.getname()); // name1
alert(p.name); // undefined
Here the property name is private and the method getname is public, we also call it a Privileged Method, which means a public method to access private variables.

Lets see little complex example -
function Person(){
    var name = 'name1';
    this.getname = function(){
        return name;
    }
    var detail = {
        salary:1000,
        address : 'abcd',
        company:'Company1'
    }
    this.getdetails = function() {
        return detail;
    }
}
var p = new Person();
var detail = p.getdetails();
detail.company = 'new company';
In the above example even if the detail is private, but still because of getdetail method, the original object of detail get return. In order to avoid such circumstances, create a copy of the object and then return.
Or else create another object with only required detail, for example if you dont want to give the detail of salary, create another object with address and company detail in it. This is also known is Principle Of Least Authority(POLA).

No comments:

Post a Comment