Pawan Nogariya Pawan Nogariya - 2 years ago 103
Javascript Question

Javascript : How to add getter to an existing object

I can have getter in javascript object like this

var member = {
get fullName(){ return (this.firstName + ' ' + this.lastName); }

And I can even add more properties on the fly like this

member.isGuest = true;

But is there any way we can add getters to already existing object? Something like this

member.isGuest = get isGuest(){ return this.firstName=='Guest';}

Answer Source

try defineProperty

Object.defineProperty(member, 'isGuest', {
  get: function() { return this.firstName=='Guest' }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download