A normal code Snippet
Notice that
Encapsulated code snippet
In here,
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
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