Javascript : How to add getter to an existing object
I can have a getter in a JavaScript object like this:
var member = {
firstName:"XYZ",
lastName:"zzz",
get fullName(){ return (this.firstName + ' ' + this.lastName); }
}
I can even add more properties on the fly, like this:
member.isGuest = true;
But, is there any way we can add getters to an existing object? Something like this:
member.isGuest = get isGuest(){ return this.firstName=='Guest'; }
try defineProperty
Object.defineProperty(member, 'isGuest', {
get: function() { return this.firstName=='Guest' }
});
You can use the new Object.defineProperty this way:
Object.defineProperty(
member,
'prop',
{
get: function() {
return this.lastName.toUpperCase()
}
}
);
In the past you had to use __defineGetter__
but now it has been deprecated.