In JavaScript, accessor properties are methods that get or set the value of an object. For that, we use these two keywords:
get
- to define a getter method to get the property valueset
- to define a setter method to set the property value
If you want a value that's based on some other values: someone's full name, for example, is a concatenation of their first and last names.
// Ugly
person.setLastName('Smith');
person.setFirstName('Jimmy');
person.getFullName(); // Jimmy Smith
Getter ans setter save you!
var person = {
firstName: 'Jimmy',
lastName: 'Smith',
get fullName() {
return this.firstName + ' ' + this.lastName;
},
set fullName (name) {
var words = name.toString().split(' ');
this.firstName = words[0] || '';
this.lastName = words[1] || '';
}
}
person.fullName = 'Jack Franklin';
console.log(person.firstName); // Jack
console.log(person.lastName) // Franklin
you can also use Object.defineProperty()
method to add getters and setters.
Object.defineProperty(obj, prop, descriptor)
let student = {
firstName: 'Monica'
}
// getting property
Object.defineProperty(student, "getName", {
get : function () {
return this.firstName;
}
});
// setting property
Object.defineProperty(student, "changeName", {
set : function (value) {
this.firstName = value;
}
});
console.log(student.firstName); // Monica
// changing the property value
student.changeName = 'Sarah';
console.log(student.firstName); // Sarah