Encapsulation in JavaSript

Example for OOP Concept of encapsulation in JavaScript

HTML

<textarea readonly id="output"></textarea>

JavaScript

/* Example for quiz application will have users (a Users Function) who take the quiz. There will be some common properties for every user who takes the quiz: each user will have a name, a score, an email, and the quiz scores (all the scores). These are the properties of the User object. In addition, each User object should be able to show the name and score, save scores, and change the email. These are the methods of the object. */


function user(theName, theEmail) {
  this.name = theName;
  this.email = theEmail;
  this.quizScores = [];
  this.currentScore = 0;
}
user.prototype = {
  constructor: user,
  saveScore: function(newScore) {
    this.quizScores.push(newScore);
  },
  showNameAndScore: 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;
  }
}
firstUser = new user('Sendil','[email protected]');
firstUser.changeEmail('[email protected]');
firstUser.saveScore(12);
firstUser.saveScore(18);

var result = document.getElementById('output');
result.innerHTML = firstUser.showNameAndScore();