我有一个类 "House",如下:
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 */});
在构造函数中,我是否必须检查“params”中的所有值以插入到正确的属性(嵌套对象)中?
我想避免创建其他类,如地址和访问,在house构造函数中创建每个实例的新实例。最佳实践是什么?
谢谢!
Object.assign(this,params)
会起作用吗? - Sebastian Speitel