Javascript is a popular programming language that is widely used for developing web applications. One of the key features of Javascript is its support for getters and setters, which are functions used to retrieve and set values of object properties.
Getters and Setters are functions used to retrieve and set the values of object properties in Javascript.
They provide an alternative to traditional property access by allowing developers to control how values are accessed and modified.
Getters and setters are defined using the keywords "get" and "set" respectively, followed by the name of the property they are associated with.
For example:
Consider an object representing a person whose property is name.
Traditional property access would involve accessing these properties directly:
class Person {
constructor(value) {
this._name = value;
}
get name(){
return this._name;
}
set name(value){
this._name = value;
}
}
const person1 = new Person("Paul");
console.log(person1.name); //Paul
person1.name = "John";
console.log(person1.name); //John
When developing getter and setter we have to take into account the following:
nameObject.setterMethod = property
There are several benefits to using getters and setters in Javascript:
You can use the get method inside an object using the same method for an element of the object.
If one element of the object is an array, the other element of the object will be a get method that can retrieve elements from the array.
var colorObj = {
colors: ['yellow', 'black'],
get firstElement() {
return this.colors[0];
}
};
console.log('First Element: '+colorObj.firstElement);
We can delete the get method using the "delete" keyword.
You can use the Set method inside an object using the same method to set values to another element of the object.
If one element of the object is an array, the other element of the object will be a set method that can add elements to the array.
var colorObj = {
colors: ['yellow', 'black'],
set setValue(val) {
this.colors.push(val);
}
};
colorObj.setValue = 'Red';
colorObj.setValue = 'White';
console.log('All colors: '+colorObj.colors);
It is possible to delete a get or set method by using the delete keyword followed by the name of the method to delete.
var colorObj = {
colors: ['yellow', 'black'],
get lastElement() {
return this.colors[this.colors.length - 1];
},
set setValue(val) {
this.colors.push(val);
}
};
console.log('Adding color red');
colorObj.setValue = 'Red';
console.log('All Elements: '+colorObj.colors);
console.log('Removing method setValue');
delete colorObj.setValue;
console.log('Adding color White');
colorObj.setValue = 'White';
console.log('All Elements: '+colorObj.colors);
console.log('Last Element: '+colorObj.lastElement);
console.log('Removing method lastElement');
delete colorObj.lastElement;
console.log('Last Element: '+colorObj.lastElement);
console.log('All Elements: '+colorObj.colors);
Tips on SEO and Online Business
Next Articles
Previous Articles