简体   繁体   English

带有getter和setter的javascript对象

[英]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: 我对此对象有4个要求:

  • 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. 我不确定这是否是使用getter和setter定义对象的最简单方法。 Is there an alternative to using defineProperty, or is this the new norm? 有没有使用defineProperty的替代方法,还是这是新规范?

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 . 这种方法还需要我编写自己的stringify方法(请参见下文),因为调用JSON.stringify将剥离函数,并且将剥离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: 另外,我必须提供一个可选的构造函数arg,以便能够从JSON对象实例化Car:

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 ). 要在使用JSON.stringify显示make属性,必须将enumerable设置为True (默认情况下为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. configurable :当且仅当可以更改此属性描述符的类型并且可以从相应对象中删除该属性时,才为true Defaults to false . 默认为false

enumerable : true if and only if this property shows up during enumeration of the properties on the corresponding object. enumerable :当且仅当在枚举相应对象的属性期间显示此属性时,才返回true Defaults to false . 默认为false function Car() { 函数Car(){

var _make;

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

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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