Thursday, December 29, 2011

Javascript Private Members


Javascript does not have special syntax for private members however they can be implement by using closure in object constructor and using wrap function in object literal. Examples below shows how private members can be implemented.

Example 1. Object Constructor

function Grocery(){
    //private
    var type='fruit';
    
    //public
    this.getType=function(){
        return type;
    }
}
var orange=new Grocery();
alert(orange.type); //undefined
alert(orange.getType()); //fruit

Example 2. Object Literal

var orange;
(function(){
    //private
    var type="fruit";
    
    //public
    orange={
        getType:function(){
            return type;
        }
    };
}());
alert(orange.getType());//fruit

No comments:

Post a Comment