Encapsulation : private variables in JavaScript

Encapsulation is an one of main concepts in object oriented programming. Encapsulation is the ability that an object has to forbid external access to chosen properties and methods, so that they can only be called by other methods of same object and protect from external unwanted access.

A normal code Snippet

function SecretCode(){
    secretNumber=Math.floor((Math.random() * 10) + 1);     
    
    this.getSecret=function(){
        return secretNumber;
    }
}

var secret1 = new SecretCode();
document.write("value of secret number "+secret1.secretNumber+"<br/>");

document.write("value of secret number : "+secret1.getSecret()+"<br/>");

SecretCode.prototype.getSecretCode= function(){
    return this.secretNumber;    
}

document.write("Secret number is "+secret1.getSecretCode()+"<br/>");


Notice that secretNumber property can be accessed from outside using dot notation (read more about dot notation for retrieve properties)external methods like getSecretCode() and , because the  secretNumber  property is not encapsulated.

Encapsulated code snippet

function SecretCode(){
   var secretNumber=Math.floor((Math.random() * 10) + 1);     
    
    this.getSecret=function(){
        return secretNumber;
    }
}

var secret1 = new SecretCode();
document.write("value of secret number "+secret1.secretNumber+"<br/>");

document.write("value of secret number : "+secret1.getSecret()+"<br/>");

//cant access protected properties even with prototype functions
SecretCode.prototype.getSecretCode= function(){
    return this.secretNumber;    
}

document.write("Secret number is "+secret1.getSecretCode()+"<br/>");


In here, secretNumber property can't be accessed from outside using dot notation external methods like getSecretCode() and , because the  secretNumber  property is encapsulated with var infront of the property declaration.
ex: var secretNumber=Math.floor((Math.random() * 10) + 1);
Plrase add a comment if something is not clear to you or you have some thing to add

No comments:

Post a Comment