2 回答
TA贡献1864条经验 获得超2个赞
function safeProps(func, defaultVal) {
try {
return func();
} catch (e) {
return defaultVal;
}
}
safeProps(function(){
student = obj.school.class1.student
}, -1)
TA贡献1809条经验 获得超8个赞
如果不用考虑兼容性的话,加个Proxy
监听get
是个很合适的办法
/**
* @param target
* @param exec 取值属性
* @returns {*}
*/
function getter(target, exec = '_') {
return new Proxy({}, {
get: (o, n) => {
return n === exec ?
target :
getter(typeof target === 'undefined' ? target : target[n], exec)
}
});
}
let obj = {
school: {
class1: {
student: 50
}
}
};
console.log(getter(obj).school.class1.student._)//50
console.log(getter(obj).school1.class11.student._)//undefined
添加回答
举报