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

1.8k Views Asked by At

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

  • more than one instance can be created at any time
  • only properties defined on the object can be set/get
  • the object must be stringify-able (just the properties and associated values)
  • the stringified version must be parse-able and return the 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?

1

There are 1 best solutions below

0
On

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);

}