Saturday, October 25, 2014

Why is JavaScript so beautiful?

There is a common belief among people that javascript does not have all the beauties of a modern programming language, like private, public and privileged function, in all information hiding.

I am providing a few examples which showcases the beauty and power of javascript::

var biodata = function(firstName, secondName){
//Public members::
this.firstName = firstName;
this.secondName = secondName;
//This is an assignment which takes the present context and assigns it to another variable, in this case that
var that = this;
//private members:
var sex = "Male";
var relationshipStatus = "in a relationship";
//private methods:
var getSex = function(){
console.log("Person " + that.firstName + " is a " + sex);
}
getSex();
//This is a privileged function which is accessible by the outside world, but it itself has access to the private
//methods and variables.
//For instance, sex and relationshipStatus are private variable of the function biodata.
//getAllInfo (privileged function) provides access to the outside world with all these values
this.getAllInfo = function(){
var allInfo = {};
allInfo.firstName = this.firstName;
allInfo.secondName = this.secondName;
allInfo.sex = sex;
allInfo.relationshipStatus = relationshipStatus;
//This is a public member in the public function, collegeInfo of biodata and is accessible using this.
allInfo.collegeName = this.collegeName;
return allInfo;
}
}
//public method in prototype
biodata.prototype.collegeInfo = function(collegeName){
this.collegeName = collegeName;
console.log("Person:" + this.firstName + " studied in " + this.collegeName);
}
var obj = new biodata("Sylvestor", "Stallone");
obj.collegeInfo("University of Miami");
var hackInfo = obj.getAllInfo();
console.log("FirstName:", hackInfo.firstName);
console.log("secondName:", hackInfo.secondName);
//The privileged method provides access to private variables of a function
console.log("sex:", hackInfo.sex);
console.log("relationshipStatus:", hackInfo.relationshipStatus);
console.log("collegeName:", hackInfo.collegeName);


I hope u liked the post. Leave comments if you have any suggestions or want to learn more.