JavaScript Object Accessors
There are two keywords that define the accessors functions: a getter and a setter for the fullName property. When the property is accessed, the return value from the getter is used. When a value is set, the setter is called and passed the value that was set.
JavaScript Getter (The get Keyword)
Example: This example describes the use of the lang() property to get the value of the language property.
Javascript
// Create an object: const person = { name: "w3wiki" , get lang() { return this .name; } }; // Display data from the //object using a getter console.log(person.name); |
w3wiki
JavaScript Setter (The set Keyword)
Example: This example describes the use of the lang() property to set the value of the language property.
Javascript
// Create an object: const person = { name: "w3wiki" , set lang(value) { return this .name; } }; // Display data from the //object using a getter console.log(person.name); |
w3wiki
Note: Getters and Setters are not supported in Internet Explorer 8.
Reasons to use Getters and Setters
- The syntax for properties and methods are equal.
- Used for doing things behind the scenes.
- They can secure better data quality.
- The syntax of this is simpler.
Data Quality
The Getters and Setters are used to secure better data quality. In the given example below, using the lang property, the lowercase value of the language is returned.
Example: This example uses the lang property and it returns the lowercase value of the language.
Javascript
const person = { language: "w3wiki" , get lang() { return this .language.toLowerCase(); } }; // Display data from the //object using a getter console.log(person.lang); |
w3wiki
Contact Us