给定一个 Object,实现一个代理函数,使得取值安全,且在末端使用函数调用的方式传入默认值
JavaScript 实现
function dataProxy(data) {
const dataType = typeof data;
const fn = d => dataType === 'undefined' ? d : data;
return new Proxy(fn, {
get(target, property) {
if (dataType === 'undefined' || data === null) return dataProxy();
return dataProxy(data[property]);
}
});
}
const data = {
res: true,
data: {
count: 1
}
};
const proxyData = dataProxy(data);
console.log(proxyData.res());
console.log(proxyData.data());
console.log(proxyData.data.count());
console.log(proxyData.b.c.d('自定义'));
Python 实现
class dataProxy:
def __init__(self, data=None):
self._dict = data
def __getattr__(self, name):
if isinstance(self._dict, dict) and name in self._dict:
return dataProxy(self._dict[name])
else:
return dataProxy()
def __call__(self, default=None):
return self._dict if self._dict is not None else default
data = {
'res': True,
'data': {
'count': 1
}
}
proxyData = dataProxy(data)
print(proxyData.res())
print(proxyData.data())
print(proxyData.data.count())
print(proxyData.b.c.d('自定义'))