A getter is a method that gets the value of a specific property and setter is a method that sets the value of a specific property. The getters and setters method can be defined on any predefined core objects or the user defined objects that supports the addition of new properties.
Example :
var obj = {
a : 7,
get b(){
return this.a * 2;
},
set c(x){
this.a = x/ 5;
}
};
console.log(obj.a); // 7
console.log(obj.b); // 14
obj.c = 100;
console.log(obj.a); // 20
The obj object properties are :
obj.a ==> a number
obj.b ==> a number multiplied with 2.
obj.a ==> a number sets the value of obj.c/5;
The getters and setters can extend the Date property to add a year property to all the instances of the predefined Date class. It uses getFullYear and setFullYear methods to support the year property's getter and setter.
var a = Date.prototype;
Object.defineProperty(a, 'year', {
get: function() { return this.getFullYear(); },
set: function(y) { this.setFullYear(y); }
});
var today= new Date();
console.log(today.year); //2017
today.year = 2001;
console.log(today); //Mon Dec 03 2001 20:45:11 GMT+0530 (India Standard Time)
The getters and setters can be defined in two ways :
Example :
var obj = {
a : 7,
get b(){
return this.a * 2;
},
set c(x){
this.a = x/ 5;
}
};
console.log(obj.a); // 7
console.log(obj.b); // 14
obj.c = 100;
console.log(obj.a); // 20
The obj object properties are :
obj.a ==> a number
obj.b ==> a number multiplied with 2.
obj.a ==> a number sets the value of obj.c/5;
The getters and setters can extend the Date property to add a year property to all the instances of the predefined Date class. It uses getFullYear and setFullYear methods to support the year property's getter and setter.
var a = Date.prototype;
Object.defineProperty(a, 'year', {
get: function() { return this.getFullYear(); },
set: function(y) { this.setFullYear(y); }
});
var today= new Date();
console.log(today.year); //2017
today.year = 2001;
console.log(today); //Mon Dec 03 2001 20:45:11 GMT+0530 (India Standard Time)
The getters and setters can be defined in two ways :
- It can be defined using object initializer.
- It can be added later to any object at any time using getter or setter method.
when getter and setter methods are defined using object initiallizer, we just need to do is, add a prefix i.e, for getter method with get and setter method with set. The getter method must not take any parameters and setter methods exactly one parameters.
var obj = {
a:7;
get b(){}
set c(x){}
};
Getters and Setters can also be added to an object at any time using the Object.defineProperties method.
Example :
var obj = { a : 7 };
Object.defineProperties(obj, {
'b': { get: function() { return this.a + 1; } },
'c': { set: function(x) { this.a = x / 2; } }
});
obj.c = 10;
console.log(obj.a); // 5
console.log(obj.b); // 6
No comments:
Post a Comment