Encapsulation
Data binding
- Use var keyword to make data members private.
- Use setter methods to set the data and getter
methods to get that data.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<h2 style="background-color:
rgb(9, 238, 9);color:rgb(255, 0, 0);font-weight: bolder;font-family: Georgia,
'Times New Roman', Times, serif;">Encapsulation</h2>
<h5 style="color:
rgb(231, 15, 166);">Output</h5>
</head>
<body>
<script>
class Student
{
constructor()
{
var name;
var marks;
}
getName()
{
return this.name;
}
setName(name)
{
this.name=name;
}
getMarks()
{
return this.marks;
}
setMarks(marks)
{
this.marks=marks;
}
}
var stud=new Student();
stud.setName("Gubenthiran");
stud.setMarks(90);
document.writeln(stud.getName()+" "+stud.getMarks());
</script>
</body>
</html>
Output
Prototype
based Encapsulation
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<h2 style="background-color:
rgb(9, 238, 9);color:rgb(255, 0, 0);font-weight: bolder;font-family: Georgia,
'Times New Roman', Times, serif;">Encapsulation</h2>
<h5 style="color:
rgb(231, 15, 166);">Output</h5>
</head>
<body>
<script>
function Student(name,marks)
{
var s_name=name;
var s_marks=marks;
Object.defineProperty(this,"name",{
get:function()
{
return s_name;
},
set:function(s_name)
{
this.s_name=s_name;
}
});
Object.defineProperty(this,"marks",{
get:function()
{
return s_marks;
},
set:function(s_marks)
{
this.s_marks=s_marks;
}
});
}
var stud=new Student("Rosy",70);
document.writeln(stud.name+" "+stud.marks);
</script>
</body>
</html>
Output
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<h2 style="background-color:
rgb(9, 238, 9);color:rgb(255, 0, 0);font-weight: bolder;font-family: Georgia,
'Times New Roman', Times, serif;">Encapsulation</h2>
<h5 style="color:
rgb(231, 15, 166);">Output</h5>
</head>
<body>
<script>
class Stu
{
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 std=new Stu();
var std1=new Stu();
std.setName("Raj");
std.setMarks(110);
std1.setName("Priya");
std1.setMarks(99);
document.writeln(std.getName()+"
"+std.getMarks());
document.writeln(std1.getName()+" "+std1.getMarks());
</script>
</body>
</html>
Output
0 comments:
Post a Comment