ECMAScript 5 (ES5, 2009) introduced getters and setters, which enable the definition of object accessors (computed properties).
This example uses a lang property to retrieve the value of the language property.
// Create an object: const person = { firstName: “John”, lastName: “Doe”, language: “en”, get lang() { return this.language; } }; // Display data from the object using a getter: document.getElementById(“demo”).innerHTML = person.lang; |
This example uses a lang property to assign a value to the language property.
const person = { firstName: “John”, lastName: “Doe”, language: “”, set lang(lang) { this.language = lang; } }; // Set an object property using a setter: person.lang = “en”; // Display data from the object: document.getElementById(“demo”).innerHTML = person.language; |
What are the differences between these two examples?
const person = { firstName: “John”, lastName: “Doe”, fullName: function() { return this.firstName + ” “ + this.lastName; } }; // Display data from the object using a method: document.getElementById(“demo”).innerHTML = person.fullName(); |
const person = { firstName: “John”, lastName: “Doe”, get fullName() { return this.firstName + ” “ + this.lastName; } }; // Display data from the object using a getter: document.getElementById(“demo”).innerHTML = person.fullName; |
In Example 1, fullName is accessed as a function: person.fullName().
In Example 2, fullName is accessed as a property: person.fullName.
The second example offers a simpler syntax.
JavaScript can ensure better data quality by using getters and setters.
In this example, the lang property returns the value of the language property in uppercase.
// Create an object: const person = { firstName: “John”, lastName: “Doe”, language: “en”, get lang() { return this.language.toUpperCase(); } }; // Display data from the object using a getter: document.getElementById(“demo”).innerHTML = person.lang; |
In this example, the lang property stores an uppercase value in the language property.
const person = { firstName: “John”, lastName: “Doe”, language: “”, set lang(lang) { this.language = lang.toUpperCase(); } }; // Set an object property using a setter: person.lang = “en”; // Display data from the object: document.getElementById(“demo”).innerHTML = person.language; |
The Object.defineProperty() method can also be used to define 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; |