Javascript Practice Day2 : Properties in Javascript and add validations
We can add properties in Javascript same way we do in other object oriented programming language to keep the encapsulation property .We use "Object.defineProperty " to create property around private variable there by adding validation /restriction on changing the values of the variables
//constructor function
function student(name,age)
{
//private variable
var _name=name;
var _age= age;
//constructor function
function student(name,age)
{
//private variable
var _name=name;
var _age= age;
//declaring the property on age and restricting it to 1-100 , on giving more that 100 it throws an alert
Object.defineProperty(this,"age",{
get : function(){
return _age;
},
set : function() {
if(value<1 || value >100){
alert("Invalid age");
}
else{
_age=value;
}
}
})
//declaring the property on name and making it readly , name is a private variable and can be accessed only through property
Object.defineProperty(this,"name",{
get: function(){
return _name;
}
})
}
//object John is created out of student and '30' is passed as a parameter
var John= new student("John",30);
document.write(John.name +"<br\>");
document.write(John.age +"<br\>");
//since age is public the value is changed to 1000 which throws alert
//John.age=1000;
Comments
Post a Comment