user1491636
user1491636

Reputation: 2446

How to define a constructor function that makes objects with getters and setters?

I'm working on creating an object definition to encapsulate several properties. I have 4 requirements for this object:

This is a simplified version of what I have so far:

function Car() {
    
    var _make;

    Object.defineProperty(this, 'make', {
        get: function() {
            return _make;
        },
        set: function(make) {
            _make = make;           
        }
    });
    Object.preventExtensions(this);
}

I'm unsure if this is the simplest approach for defining an object with getters and setters. Is there an alternative to using Object.defineProperty, or is this the new norm?

This approach also requires me to write my own stringify method (see below) since calling JSON.stringify will strip off functions, and this will strip off make. Is there an alternative to writing my own? Can I change my object definition somehow?

Car.prototype.stringify = function () {
    return JSON.stringify({ make: this.make});
}

Additionally, I must supply an optional constructor arg to be able to instantiate a Car from a JSON object:

function Car(car) {
    var _make;
    if(car !== undefined && car != null) {
        _make = car.make;
    }
    ...
}

Again, is this the best approach to meet all the requirements?

Upvotes: 2

Views: 1886

Answers (1)

Akshay Pratap Singh
Akshay Pratap Singh

Reputation: 3327

To show up make property while using JSON.stringify, you have to set the enumerable to True (By default, False).

configurable: true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. Defaults to false.

enumerable: true if and only if this property shows up during enumeration of the properties on the corresponding object. Defaults to false. function Car() {

var _make;

Object.defineProperty(this, 'make', {
    get: function() {
        return _make;
    },
    set: function(make) {
        _make = make;           
    },
    enumerable:true 
});
Object.preventExtensions(this);

}

Upvotes: 4

Related Questions