Encapsulation in Java Script
Encapsulation
Encapsulation refers to enclosing all the functionalities of an object within that object so that the object’s internal workings (its methods and properties) are hidden from the rest of the application.
One of the main principles with OOP is encapsulation: put all the inner workings of an object inside that object. To implement encapsulation in JavaScript, we have to define the core methods and properties on that object.
To do this, we will use the best pattern for encapsulation in JavaScript: the Combination Constructor/Prototype Pattern.
Implementation of Combination Constructor/Prototype Pattern
Example:
function User (theName, theEmail) {
this.name = theName;
this.email = theEmail;
this.quizScores = [];
this.currentScore = 0;
}
Implementation of Combination Constructor/Prototype Pattern
The Above lines initialize the instance properties. These properties will be defined on each User instance that is created.
So the values will be different for each user.
The use of the this keyword inside the function specifies that these properties will be unique to every instance of the User object:
User.prototype = {
constructor: User,
saveScore:function (theScoreToAdd) {
this.quizScores.push(theScoreToAdd)
},
showNameAndScores:function () {
var scores = this.quizScores.length > 0 ? this.quizScores.join(",") : "No Scores Yet";
return this.name + " Scores: " + scores;
},
changeEmail:function (newEmail) {
this.email = newEmail;
return "New Email Saved: " + this.email;
}
}
In the code above, we are overwriting the prototype property with an object literal, and we define all of our methods (that will be inherited by all the User instances) in this object.
Make Instance of the User Function
// A User
firstUser = new User(“Sharjeel", “Sharjeel.bilali@example.com");
firstUser.changeEmail(“Sharjeel.bilali @edynamic.net");
firstUser.saveScore(15);
firstUser.saveScore(10);
firstUser.showNameAndScores(); //Sharjeel Scores: 15,10
// Another User
secondUser = new User(“Affan", “Affan@example.com");
secondUser.saveScore(18);
secondUser.showNameAndScores(); //Affan Scores: 18
Comments
Post a Comment