I have a need to perform some action whenever an object is changed, and feel that setters might be a good option, and am researching getters and setters for the first time. While I believe setters can sometime provide benefit, I don't really do so for getters. Sure, it "might" make my script a little easier to read but at the expense of making it a little more magical, but it seems like one could just as well add whatever functionality the getter would be performing in the function.
I am not asking whether getters are a good thing or not, but just a couple common applications where they provide significant benefit so that I can get my head wrapped around them and be able to identify applicable specific opportunities to use them in the future.
var person_w_getter = {
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] || '';
}
}
console.log('with getter');
person_w_getter.fullName = 'Jack Franklin';
console.log(person_w_getter.firstName); // Jack
console.log(person_w_getter.lastName) // Franklin
var person_wo_getter = {
firstName: 'Jimmy',
lastName: 'Smith',
getFullName: function() {
return this.firstName + ' ' + this.lastName;
},
setfullName: function(name) {
var words = name.toString().split(' ');
this.firstName = words[0] || '';
this.lastName = words[1] || '';
}
}
console.log('without getter');
person_wo_getter.setfullName('Jack Franklin');
console.log(person_wo_getter.firstName); // Jack
console.log(person_wo_getter.lastName) // Franklin