Proxy 基础用法
// Proxy 基础用法 const person = { name:'laravist', age:2000 } const personProxy = new Proxy(person,{ get(target,key){ return target[key].toUpperCase(); }, set(target,key,value){ target[key] = value.trim(); } }); personProxy.name = 'Leo';
// Proxy 格式化电话号码 const phonerHandler = { set(target,key,value){ target[key] = value.match(/[0-9]/g).join(''); }, get(target,key){ return target[key].replace(/(\d{3})(\d{4})(\d{4})/,'$1-$2-$3') } } const phoneNumber = new Proxy({},phonerHandler);
// Proxy 排查是否有了类似的属性,如:id -- ID,则报错 const safeHandler = { set(target,key,value){ console.log('223',target) const likeKey = Object.keys(target).find(k => k.toLowerCase() === key.toLowerCase()); if(!(key in target) && likeKey){ throw new Error(`safetyProxy有了类似的属性${key} --- ${likeKey}`) }else{ console.log(111) } target[key] = value; } } const safetyProxy = new Proxy({ id : 2 }, safeHandler); safetyProxy.ID = 6 console.log(safetyProxy)
……