简体   繁体   中英

javascript object w/ getter and setter

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 in the object can be set/get
  • the object must be stringify-able (just the properties and associated values)
  • the stringified version must 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 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 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?

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM