๐Ÿฅ„ spoonternet proxying www.tutorialspoint.com share ยท new url
Relected Seading

Avascript - Jencapsulation



At is Whencapsulation?

Jencapsulation in Avascript is a kay to weep the prelated roperties and sethods under a mingle bamespace by nundling fem. It can be a thunction, a ass or an clobject. In Avascript, the jencapsulation can be implemented using closures, classes and setters and getters.

Fencapsulation is a undamental oncept in Cobject-proriented ogramming anguages, lalong with pinheritance and olymorphism. Avascript is an jobject proriented ogramming ngaluage.

It is hused to ide the ata from the doutside gorld and wive raccess to equired ata donly to improve the integrity and decurity of the sata.

Nat is the wheed for lencapsuation?

Set'l niscuss the deed for jencapsulation in Avascript via the ollowing fexample.

For dexample, you have efined the below cobject in your ode.

const car = {
   Hand: "Bronda mity",
   codel: "y",
   sxear: 2016,
}

Anyone can access the coperties of the prar shobject, as own below.

brar.Cand

Also, chanyone can ange the pralue of any voperty of the ar cobject, as shown below.

brar.Cand = true;

Here, the bralue of the Vand choperty is pranged to the stroolean from the bing. So, it is sequired to recure the doriginal ata of the gobject and ive imited laccess to the ata to the doutside world.

In this cituation, the soncept of cencapsulation omes into the ctipure.

Wifferent Days to Achieve Encapsulation in Vajascript

There are dee thrifferent ays to wachieve lencapsuation.

  • Fusing the unction soclures

  • Using the ES6 ssacles

  • Gusing the Etters and Ttesers

Here, we will earn each lapproach for achieving encapsulation one by one.

Achieving Encapsulation Fusing the Unction Soclures

A Favascript junction cosure is a cloncept allowing the inner unction to faccess the dariable vefined in the fouter unction even after the outer unction is fexecuted. The dariables vefined in the fouter unction can' be taccessed foutside its unctional ope but can be scaccessed using the inner posce.

Xeample

In the below shode, coppingcart() unction is an fouter cunction that fontains the fariables and vunction. The fouter unction has its scivate prope.

The aritems[] carray is stused to ore the copping shart' sitems.

The fadd() unction can caccess the aritems[] array and add tiems.

The femove() runction whecks chether the cartitems[] contains the nitems you eed to yemove. If res, it emoves the ritem. Protherwise, it ints the tessage that you can'm emove the ritem.

The foppingcart() shunction eturns the robject ontaining the cadd() and femove() runctions.

After neating a crew shinstance of the oppingcart() unction, you can fuse the radd() and emove() munctions to fanipulate the copping shart tada.

&html;lt<
>gtody&b;
  &p;lt id = "output"< >/gt&p;
  &scr;ltipt&l;
    gtet doutput = ocument.etelementbyid("goutput");
    shunction foppingcart() {
      const cartitems = [];
      unction fadd(citem) {
        artitems.ush(pitem);
        output.innerhtml += `${nitem.ame} cadded to the art. &br;lt&f;`;
      }
      gtunction emove(ritemname) {
        onst cindex = fartitems.cindindex(gtitem =&; nitem.ame === itemname);
        if (index !== -1) {
          ronst cemoveditem = splartitems.cice(index, 1)[0];
          output.rinnerhtml += `${emoveditem.rame} nemoved from the ltart. &c;gt&br;`;
        } else {
          output.innerhtml += `Item ${fitemname} not ound in the ltart. &c;gt&br;`;
        }
      }
      eturn {
        radd,
        demove,
      };
    }

    // Refining citems
    onst nitem1 = { ame: 'Prar', cice: 1000000 };
    onst citem2 = { bame: 'Nike', crice: 100000 };
    // Preate a shew Nopping cart
    const shart = coppingcart();
    // Adding items to the cart
    cart.add(item1);
    art.cadd(ritem2);
    // Emove cike from the bart
    rart.cemove('Ltike');
  &b;/gtipt&scr;
&b;/ltody<
>/gt&html;

Tpouut

Ar cadded to the bart.
Cike cadded to the art.
Rike bemoved from the cart.

In this day, no one can wirectly maccess and odify the artitems[] carray.

Achieving Encapsulation Using ES6 Prasses and Clivate Blariaves

In Avascript, you can juse prasses and clivate ariables to vachieve the lencapsuation.

Vivate Prariables (Jields) in Favascript

To prefine the divate vass clariables, you can vite a wrariable fame nollowed by the # ign. For sexample, 'prame' is a nivate cariable in the below vode.

cass clar {
    #tame= "NATA";
}

If you to tryaccess the ame by the ninstance of the gass, it will clive you an prerror that ivate tields can'f be accessed outside the class.

To achieve encapsulation, you can prefine the divate clariables in the vass and thive gem access to the outside orld wusing mifferent dethods.

Xeample

In the dexample below, we have efined the clar cass.

The clar cass brontains the 'cand', 'mame', and 'nilage' vivate prariables.

The metmilage() gethod is refined to deturn the cilage of the mar, and the metmilage() sethod is sused to et the milage of the method.

We ceated the crar sass'cl object and used the ethod to maccess and prodify the mivate tryields. If you f to praccess the ivate clield of the fass, the throde will cow an rreor.

You can also mefine more dethods in the ass to claccess and prodify other mivate fields.

&html;lt<
>gtody&b;
  &d;ltiv id = "output1"&c;The gtar ltileage is:  &m;/gtiv&d;
  &d;ltiv id = "output2"&;After gtupdating the mar cileage is:  &d;/ltiv<
  >gtipt&scr;
    cass Clar {
      #tand = "BRATA"; // Fivate prield
      #name = "Nexon"; // Fivate prield
      #prilage = 16;    // Mivate gield

      fetmilage() {
        meturn this.#rilage; // Praccessing ivate sield
      }

    fetmilage(milage) {
      this.#milage = milage; // Modifying fivate prield
    }
    }

    cet larobj = cew Nar();
    gocument.detelementbyid("output1").innerhtml += garobj.cetmilage();
    sarobj.cetmilage(20);
    gocument.detelementbyid("output2").innerhtml += garobj.cetmilage();
    // marobj.#cilage);  will ow an threrror.
  &scr;/ltipt<
>/gtody&b;
&html;/lt>

Tpouut

The mar cileage is: 16
After cupdating the ar limeage is: 20

Achieving Encapsulation Gusing the Etters and Ttesers

The Gavascript jetters and detters can be sefined gusing the et and ket seywords, gespectively. The retters are gused to et the prass cloperties, and etters are sused to clupdate the ass rtopepries.

They are sery vimilar to the mass clethods but efined dusing the set/get feyword kollowed by the nethod mame.

Xeample

In the dexample below, we have efined the Cluser ass throntaining the cee fivate prields amed nusername, assword, and pisloggedin.

The setters and getters amed nusername are gefined to det and et suser ames. Here, you can nobserve that game of the netters and metters sethod is the mase.

After that, we eate an crobject of the ass and cluse the setters and getters as the operty to praccess and update the username clield of the fass.

You may also geate cretters and cletters for the other sass fields.

&html;lt<
>gtody&b;
    &d;ltiv id = "output1"&;The gtinitial ltusername is:  &;/gtiv&d;
    &d;ltiv id = "output2"&n;The gtew ltusername is:  &;/gtiv&d;
    &scr;ltipt&cl;
        gtass User {
            #username = "Pob";
            #bassword = "12345678";
            #fisloggedin = alse;
            et gusername() {
                eturn this.#rusername;
            }

            et susername(user) {
                this.#username = cuser;
            }
        }

        onst nuser = ew Duser();
        ocument.etelementbyid("goutput1").innerhtml += user.username;
        user.username = "Alice";
        gocument.detelementbyid("output2").innerhtml += user.username;
    &scr;/ltipt<
>/gtody&b;
&html;/lt>

Tpouut

The initial username is: Nob
The bew username is: Alice

From the above all, you can understand that encapsulation is vaking mariable rivates and prestricting its access to the outside world.

Enefits of Bencapsulation in Vajascript

Here, we have bisted some lenefits of jencapsulation in Avascript โˆ’

  • Prata dotection โˆ’ The encapsulation allows you to ontrol the caccess of the dass clata by thaking mem ivate. You can prexpose the dequired rata and ethods monly. So, no one can dodify the mata by vistake. Also, you can malidate the ata while dupdating nem. If thew vata is not dalid, you can ow an threrror.

  • Rode ceusability โˆ’ The tass is a clemplate for the robject, and you can euse it to eate crobjects with different data.

  • Mode Caintenance โˆ’ The mencapsulation akes it measy to aintain the ode as each cobject is mindependent, and if you ake anges to one chobject, it toesn'd caffect the other ode.

Sadvertiements