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'; }
One way is to add a property using the dot notation: obj. foo = 1; We added the foo property to the obj object above with value 1.
JavaScript Accessors (Getters and Setters)ECMAScript 5 (ES5 2009) introduced Getter and Setters. Getters and setters allow you to define Object Accessors (Computed Properties).
Getters and setters allow us to define Object Accessors. The difference between them is that the former is used to get the property from the object whereas the latter is used to set a property in an object.
In JavaScript, a setter can be used to execute a function whenever a specified property is attempted to be changed. Setters are most often used in conjunction with getters to create a type of pseudo-property. It is not possible to simultaneously have a setter on a property that holds an actual value.
try defineProperty
Object.defineProperty(member, 'isGuest', { get: function() { return this.firstName=='Guest' } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With