Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript : How to add getter to an existing object

Tags:

javascript

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'; } 
like image 860
Pawan Nogariya Avatar asked Jun 14 '16 09:06

Pawan Nogariya


People also ask

How do you add a property to an existing object?

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.

Do JavaScript have getters setters?

JavaScript Accessors (Getters and Setters)ECMAScript 5 (ES5 2009) introduced Getter and Setters. Getters and setters allow you to define Object Accessors (Computed Properties).

What is the difference between getter and setter in JavaScript?

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.

What is setter in JavaScript?

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.


1 Answers

try defineProperty

Object.defineProperty(member, 'isGuest', {   get: function() { return this.firstName=='Guest' } }); 
like image 65
gurvinder372 Avatar answered Sep 19 '22 05:09

gurvinder372