Loading Please Wait...
ECMAScript 5 (ES5 2009) introduced Getter and Setters.
Getters and setters allow you to define Object Accessors (Computed Properties).
The get syntax binds an object property to a function that will be called when that property is looked up.
const user = {
name: "John",
city: "New York",
language: "English",
get lang() {
return this.language;
}
};
alert(user.lang); // "English"
The set syntax binds an object property to a function to be called when there is an attempt to set that property.
const user = {
name: "John",
city: "New York",
language: "English",
set lang(value) {
this.language = value;
}
};
user.lang = "Hindi";
alert(user.language); // "Hindi"
const user = {
firstName: "John",
lastName: "Doe",
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
alert(user.fullName()); // "John Doe"
const user = {
firstName: "John",
lastName: "Doe",
get fullName() {
return this.firstName + " " + this.lastName;
}
};
alert(user.fullName); // "John Doe"
JavaScript function access fullName as a function: person.fullName().
JavaScript getter access fullName as a property: person.fullName and provides a simpler syntax.
JavaScript can secure better data quality when using getters and setters.
const user = {
name: "John",
city: "New York",
language: "English",
get lang() {
return this.language.toUpperCase();
},
set lang(value) {
this.language = value.toUpperCase();
}
};
alert(user.lang); // "ENGLISH"
user.lang = "Hindi"
alert(user.lang); // "HINDI"
The Object.defineProperty() method can also be used to add Getters and Setters
// Define object
const obj = {counter : 0};
// Define setters and getters
Object.defineProperty(obj, "reset", {
get : function () {this.counter = 0;}
});
Object.defineProperty(obj, "increment", {
get : function () {this.counter++;}
});
Object.defineProperty(obj, "decrement", {
get : function () {this.counter--;}
});
Object.defineProperty(obj, "add", {
set : function (value) {this.counter += value;}
});
Object.defineProperty(obj, "subtract", {
set : function (value) {this.counter -= value;}
});
// Play with the counter:
obj.reset;
obj.add = 5;
obj.subtract = 1;
obj.increment;
obj.decrement;
How you feel about this blog:
Share this blog on:
If you find any error in the turtorials, or want to share your suggestion/feedback, feel free to send us email at: info@lynxsia.com
Contact UsWe are concern with various development process like website design & development, E-commerce development, Software development, Application development, SMS & Bulk SMS Provider, PWA Development, and many more..
Copyright ©
, Lynxsia IT Solutions, All rights reserved