Prev Demo
JavaScript
>
Encapsulation
Next Demo
Write code here
J
|
B
|
A
<!DOCTYPE html> <html> <head> <title>Demo</title> </head> <body> <h1>Example for Encapsulation</h1> <script> function Participant(myName, myEMail) { my.name = myName; //* Instance Property my.email = myEmail; //* Instance Property my.testScores = []; //* Instance Property my.presentScore = 0; //* Instance Property } //*Overwriting the Prototype property with an object literal Participant.prototype = { constructor: Participant, saveScore: function (theScoreToAdd) { my.testScores.push(theScoreToAdd) }, displayNameAndScores: function () { var scores = my.testScores.lenght > 0 ? my.testScores.join(",") : "No Scores Yet"; return my.name + "Scores:" + scores; } } changeEmail: function (newEmail){ my.email = newEmail; return "New Email Used:" + my.email; } // First Participant firstParticipant = new Participant("TechFunda", "techfunda@example.com"); firstParticipant.changeEmail("TechFunda@example.com"); firstParticipant.saveScore(25); firstParticipant.saveScore(20); firstParticipant.displayNameAndScores(); // TechFunda Scores: 25,20 alert("TechFunda Scores: 25, 20") // Second Participant secondParticipant = new Participant("DotNetFunda", "dotnetfunda@example.com"); secondParticipant.saveScore(30); secondParticipant.displayNameAndScores(); // DotNetFunda Scores: 30 // Third Participant thirdParticipant = new Participant("SheoNarayan", sheonarayan@example.com); thirdParticipant.saveScore(50); thirdParticipant.displayNameAndScores(); // SheoNarayan Score: 50 </script> <p><strong>Note:</strong> As this is the example for creating object for storing data, see the code in the left side box, we have ket many functionalities inside a Function Participant()</p> <script>alert("TechFunda Scores: 25, 20")</script> </body> </html>
Note: We DO NOT save your trial code in our database.
Output