JavaScript > Object Oriented Programming

Encapsulation in JavaScript

How to implement Encapsulation in JavaScript Object-Oriented programming?


Encapsulation is nothing but binding code and data together into a single unit and that is known as 'Encapsulation'.

It is the one of the main principle of OOP, to implement encapsulation in JavaScript, we need to define the properties and core methods on that object. 

Enacapsulation is very useful when we want to crate an object only of its kind to store some data, we can use object literal for creating an object.

The Encapsulation terminology can be used whenever we want to create objects with similar functionalities, we can encapsulate the functionalities in a Function and use that Function constructor to create the objects.

Implementation of Combination Constructor/Prototype Pattern 

    function Participant(myName, myEMail) { = myName;  //* Instance Property = 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) {
        displayNameAndScores: function () {
            var scores = my.testScores.lenght > 0 ? my.testScores.join(",") : "No Scores Yet";
            return + "Scores:" + scores;
    changeEmail: function (newEmail){
   = newEmail;
            return "New Email Used:" +;

In the above code snippet we intialize the instance properties, the values entered by each participant will be different because these properties will be defined on each participant instance that is created. 

The keyword "my" used inside the Function specifies these properties will be unique to every instance of the Participant object. 

By over writing the prototype with a new object literal all the methods organized in one place. 

Making Instanaces of the Participant function

    // First Participant
    firstParticipant = new Participant("TechFunda", "");

    firstParticipant.displayNameAndScores(); // TechFunda Scores: 25,20

    // Second Participant
    secondParticipant = new Participant("DotNetFunda", "");
    secondParticipant.displayNameAndScores(); // DotNetFunda Scores: 30

    // Third Participant
    thirdParticipant = new Participant("SheoNarayan",;
    thirdParticipant.displayNameAndScores(); // SheoNarayan Score: 50

Participant Function

In the implementation of combination constructor/protytype pattern, we created an object by hiding the functionalities in a Function.

In the Making instances of  the Paticipant function we understand how the created objects works instantly.

 Views: 4233 | Post Order: 200

Write for us

Hosting Recommendations