JSFiddle - React, Tailwind, and code Playground
by davidpauljunior
JavaScript
// Getting and setting inline
const person = {
firstName: 'Bob',
lastName: 'Smith',
get fullName() {
return this.firstName + ' ' + this.lastName;
},
set fullName (name) {
const words = name.toString().split(' ');
this.firstName = words[0] || '';
this.lastName = words[1] || '';
},
};
person.fullName = 'Gary Wombat';
console.log(person.firstName);
console.log(person.lastName);
// Gtting and setting outside of the object
// You can do a lot more this way.
// Like setting configurable and enumerable keys.
const anotherPerson = {
firstName: 'Mike',
lastName: 'Sparrow'
};
Object.defineProperty(person, 'fullName', {
get: function() {
return this.firstName + ' ' + this.lastName;
},
set: function(name) {
const words = name.toString().split(' ');
this.firstName = words[0] || '';
this.lastName = words[1] || '';
}
});
anotherPerson.fullName = 'Barry Biggle';
console.log(anotherPerson.firstName);
console.log(anotherPerson.lastName);