Javascript 如何以可靠的方式简化依赖于状态的getter?
我有一个角度组件,它使用一个类型,什么是一个易于阅读的解决方案来获取一个案例中的一个数据和另一个案例中的另一个数据 该组件也可以分为两个组件,电话组件和电子邮件组件,但大多数逻辑(尽管很小)都会重复Javascript 如何以可靠的方式简化依赖于状态的getter?,javascript,angularjs,oop,heuristics,Javascript,Angularjs,Oop,Heuristics,我有一个角度组件,它使用一个类型,什么是一个易于阅读的解决方案来获取一个案例中的一个数据和另一个案例中的另一个数据 该组件也可以分为两个组件,电话组件和电子邮件组件,但大多数逻辑(尽管很小)都会重复 var getContactInfo, hasContactInfo; if(type === 'email') { getContactInfo = function (profile) {return profile.getEmail()}; hasContactInfo = f
var getContactInfo, hasContactInfo;
if(type === 'email') {
getContactInfo = function (profile) {return profile.getEmail()};
hasContactInfo = function (profile) {return profile.hasEmail()};
} else if(scope.type === 'phone') {
getContactInfo = function (profile) {return profile.getPhone()};
hasContactInfo = function (profile) {return profile.hasPhone()};
}
我可能会根据类型使用对象映射方法:
const buildContactInfo=(getContactInfo,hasContactInfo)=>({getContactInfo,hasContactInfo});
const contactInfoByType={
电子邮件:buildContactInfo((profile)=>profile.getEmail(),(profile)=>profile.haseEmail()),
电话:buildContactInfo((profile)=>profile.getPhone(),(profile)=>profile.hasPhone())
};
然后,在呼叫时:
const contactInfo=contactInfoByType[type];
如果(!contactInfo){
抛出新错误(`No contact info matched type'${type}`);
}否则{
contactInfo.hasContactInfo(个人资料);
contactInfo.getContactInfo(个人资料);
}
我认为这很好,用过了:)