es5中对对象进行拦截使用 Object.defineProperty(),es6增加了new Proxy来增强代理拦截能力
1. 使用Proxy拦截对象,实现私有属性(下划线开头)禁止访问
let user = { name:’xxx’, age: 18, _gender: ‘male’ } user = new Proxy(user,{ get(target, key) { if(key.startsWith(‘_’){ throw new Error(‘不可访问’) } else { return target[key] } }, set(target, key, val) { if(key.startsWith(‘_’){ throw new Error(‘不可访问’) } else { return target[key] = val } } has (target, key) { if(key[0] === "_") { // key.startsWith(‘_’) return false; } return key in target; } deleteProperty(key){ if(key.startsWith(‘_’){ throw new Error(‘不可删除’) } else { delete target[key] return ture } } ownKeys(target){ return Object.keys(target).filter(key => !key.startsWith(‘_’)) } })
2. 使用Proxy拦截函数调用
let sum = (…args) =>{ let num = 0 args.forEach(item => { num += item }) return num } sum = new Proxy(sum, { // 当前函数,上下文this,参数 apply(target, ctx, agrs) { return target(…args) * 2 } })
3. 使用Proxy拦截类的构造函数
let User = class { constructor (name){ this.name = name } } User = new Proxy(User, { // 当前类,参数,目标类 constructor(target, args, newTarget){ return new target(…args) } })