Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何以可靠的方式简化依赖于状态的getter?_Javascript_Angularjs_Oop_Heuristics - Fatal编程技术网

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(个人资料);
}

我认为这很好,用过了:)