How To Use Encapsulation Using JavaScript?


Share:
Published By: Admin, Published On: Nov 24, 2021, Category: Javascript


Hello Friends,

Now let's see example of how to use encapsulation example. We will check how to use encapsulation. This is a short guide on use encapsulation in javascript. Here you will learn how to use encapsulation. Let's get started with how to use encapsulation in javascript.

Here i will give you many example how to use encapsulation using javascript.

Example : 1
<!DOCTYPE html>
<html>
    <head>
        <title>How To Use Encapsulation Using JavaScript? - MyWebtuts.com</title>
    </head>
    <body>
        <h3>How To Use Encapsulation Using JavaScript? - MyWebtuts.com</h3>
        <script>
            class Student
            {
                constructor()
                {
                    var name;
                    var marks;
                }
                getName()
                {
                    return this.name;
                }
                setName(name)
                {
                    this.name=name;
                }

                getMarks()
                {
                    return this.marks;
                }
                setMarks(marks)
                {
                    if(marks<0||marks>100)
                    {
                        alert("Invalid Marks");
                    }
                    else
                    {
                        this.marks=marks;
                    }
                }
            }
            var stud=new Student();
            stud.setName("Laravel");
            stud.setMarks(110);
            document.writeln(stud.getName()+" "+stud.getMarks());
        </script>
    </body>
</html>  
Output :
Invalid Marks(Alert Message)
Laravel undefined
Example : 2
<!DOCTYPE html>
<html>
    <head>
        <title>How To Use Encapsulation Using JavaScript? - MyWebtuts.com</title>
    </head>
    <body>
        <h3>How To Use Encapsulation Using JavaScript? - MyWebtuts.com</h3>
        <script>
            function Stud(nm,marks)
            {
                var snm=nm;
                var sMarks=marks;
                Object.defineProperty(this,"nm",{
                    get:function()
                    {
                        return snm;
                    },
                    set:function(snm)
                    {
                        this.snm=snm;
                    }
                });
                Object.defineProperty(this,"marks",{
                    get:function()
                    {
                        return sMarks;
                    },
                    set:function(sMarks)
                    {
                        this.sMarks=sMarks;
                    }

                });
            }
            var stud=new Stud("xyz",40);
            document.writeln(stud.nm+" "+stud.marks);
        </script>
    </body>
</html>  
Output :
xyz 40

It will help you...

Share: