I can have a getter in a JavaScript object like this:
JavaScript
x
6
1
var member = {
2
firstName:"XYZ",
3
lastName:"zzz",
4
get fullName(){ return (this.firstName + ' ' + this.lastName); }
5
}
6
I can even add more properties on the fly, like this:
JavaScript
1
2
1
member.isGuest = true;
2
But, is there any way we can add getters to an existing object? Something like this:
JavaScript
1
2
1
member.isGuest = get isGuest(){ return this.firstName == 'Guest'; }
2
Advertisement
Answer
try defineProperty
JavaScript
1
4
1
Object.defineProperty(member, 'isGuest', {
2
get: function() { return this.firstName=='Guest' }
3
});
4