Consider this code:
// Creating an empty object, without inheriting (binding) to any prototype
var human = Object.create(null);
human.firstName = 'Saeed';
human.lastName = 'Neamati';
Now, I want to add a fullName property to this object, which returns the firstName + ' ' + lastName of the object.
Using object literal notation, I can simply write a getter function this way:
var human = {
firstName: 'Saeed',
lastName: 'Neamati',
get fullName() {
return this.firstName + ' ' + this.lastName;
}
}
But I can’t figure out how to attach a getter property to an object, which is already built somewhere else.
You can use Object.defineProperty
Where
<descriptor>can be something like: