我有一个正在创建的对象,并且该对象上有一个函数可以将数据加载到各种属性中。虽然该方法可以正常工作,但我觉得它可能是多余的。这可以用更简洁或更好的方式完成吗?
var user = {
productLine: {
userActiveValue: []
},
id: {
PACT: null,
EDIPI: null,
AKO: null,
},
name: {
first: null,
last: null,
},
DMIS: null,
region: null,
email: null,
load: true,
loadUser: function (userInfoAPIResponse) {
this.id.PACT = userInfoAPIResponse.UID;
this.id.EDIPI = userInfoAPIResponse.EDIPN;
this.id.AKO = userInfoAPIResponse.akoUserID;
this.name.first = userInfoAPIResponse.fName;
this.name.last = userInfoAPIResponse.lName;
this.DMIS = userInfoAPIResponse.dmisID;
this.region = userInfoAPIResponse.RHCName;
this.email = userInfoAPIResponse.userEmail;
console.log(this);
}
};
答案 0 :(得分:5)
function User(userInfoAPIResponse) {
this.id = {
PACT: userInfoAPIResponse.UID,
EDIPI: userInfoAPIResponse.EDIPN,
AKO: userInfoAPIResponse.akoUserID
};
this.productLine = {
userActiveValue: []
};
this.name = {
first: userInfoAPIResponse.fName,
last: userInfoAPIResponse.lName
};
this.DMIS = userInfoAPIResponse.dmisID;
this.region = userInfoAPIResponse.RHCName;
this.email = userInfoAPIResponse.userEmail;
}
var user = new User(...);
答案 1 :(得分:0)
除了使用例如user.name = {first:response.fName,last:response.lName}等等,没有。您需要自己将变量从一个对象映射到另一个对象,或者只使用响应作为用户变量。 或者,您可以将user声明为全局(或外部)作用域,并在回调函数中声明和设置子对象。这意味着你可能不得不在其他地方使用它们之前检查它们和它们的父母是否未定义,而不是简单的非空检查。