Javascript:使用json

时间:2018-10-09 17:46:04

标签: javascript json class object

我有一个“房屋”类,例如:

class House{
    constructor(params){
       this.clear();
       // this = {...params} // I know that don't work !!!
       //--
       // if(params.address !== undefined) this.address = {...params.address}
       //...
    }

    clear(){
      this.address = {
         number: null,
         street: null,
         zipcode: null,
         ton: null,
      }
      this.access = {
         doorcode: null,
         stair: null,
      }
    }
}

我想创建一个House的新实例,并在构造函数中注入多个json,如:

const h = new House({address: { /* json */ }, access: { /* json */});

或者只有一个像这样:

const h = new House({access: { /* json */});

在构造函数中,我必须检查“参数”中的所有值以插入良好的属性(嵌套对象)

我想避免创建其他类,例如地址和访问,并在内部构造函数中创建每个类的新实例。 最佳做法是什么?

致谢

3 个答案:

答案 0 :(得分:1)

您可以循环浏览参数并手动设置它们。然后,要清除,请删除所有自己的属性(未继承的属性)。

class House {
  constructor(params) {
    // set data
    Object.assign(this, params);
  }

  clear() {
    for (let key in this) {
      if (this.hasOwnProperty(key))
        this[key] = undefined;  // or `delete this[key];`
    }
  }
}

let house = new House({type: "normal", height: 40});
console.log(house, house instanceof House);

当然,您可能希望将输入键限制为预定义的设置。您可以将这些键存储在静态类变量中,并使用它们遍历constructorclear中的属性。

class House {
  constructor(params) {
    // check for invalid properties
    Object.keys(params).forEach(key => {
      if (!House.keys.includes(key)) 
        throw `Invalid paramater ${key}`;
    });
    // set data
    Object.assign(this, params);
  }

  clear() {
    for (let key in House.keys) {
      if (this.hasOwnProperty(key))
        this[key] = undefined;  // or `delete this[key];`
    }
  }
}
House.keys = ['type', 'height'];

let house = new House({type: 'normal', height: 40});
console.log(house, house instanceof House);

let error = new House({helloWorld: true});

答案 1 :(得分:1)

constructor中将Object.assign()object destructuringdefault parameters结合使用,可以很容易地实现这一目标:

class House {
  static get defaultAddress () {
    return {
      number: null,
      street: null,
      zipcode: null,
      town: null
    }
  }

  static get defaultAccess () {
    return {
      doorcode: null,
      stair: null
    }
  }

  constructor({ address = House.defaultAddress, access = House.defaultAccess } = {}) {
    this.clear()
    Object.assign(this.address, address)
    Object.assign(this.access, access)
  }

  clear () {
    const { defaultAddress, defaultAccess } = House

    Object.assign(this, { address: defaultAddress, access: defaultAccess })
  }
}

// no object
console.log(new House())
// empty object
console.log(new House({}))
// partial object
console.log(new House({ address: { number: 1, street: 'street', zipcode: 12345, town: 'town' } }))
// empty sub-objects
console.log(new House({ address: {}, access: {} }))
// partial sub-objects
console.log(new House({ address: { number: 1, street: 'street' }, access: { doorcode: 321 } }))
// complete object
console.log(new House({ address: { number: 1, street: 'street', zipcode: 12345, town: 'town' }, access: { doorcode: 321, stair: 3 } }))
.as-console-wrapper{min-height:100%!important}

答案 2 :(得分:0)

我认为您想为实例属性提供一个公共名称空间-与React的props模式类似-您还可以为要创建的每个实例指定默认值:

const defaultProps = { address: {}, access: {} };

class House {
  constructor(props = {}) {
    this.props = {...defaultProps, ...props};
  }
  clear() {
    this.props = {...defaultProps};
  }
}