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?
To show up
makeproperty while usingJSON.stringify, you have to set theenumerableto True (By default, False).}