// 获取对象中的某字段 // 使用方法:getObjField(obj, '--')('field1')('field2')('fieldN...')() export const O = (obj, def) => { const getField = (field) => { if (field) { // 字段值为 undefined 或 null 都会设置为默认值 if (obj && obj[field] !== undefined && obj[field] !== null) { obj = obj[field]; } else { obj = def; } return getField; } return obj; }; getField.toString = () => { return obj; }; getField.valueOf = () => { return obj; }; return getField; };
第一次调用传入对象和默认值(可选),以后的调用传入字段名,最后什么都不传调用获得返回值react
toString 和 valueOf 在某些状况会执行,好比 console,而 react 的 JSX 中要展现内容,仍是得执行最后的调用,不然只是返回个函数函数