/* 代理模式* 由于对象不能直接引用另一个对象,所以需要通过代理对象在这两个对象之间起到中介作用* 可以在使用者和目标对象之间加一个代理对象,通过代理可以实现控制*/class Google { get(url) { return 'google'; }}class Proxy { constructor() { this.google = new Google(); } get(url) { return this.google.get(url) }}let proxy = new Proxy()let result = proxy.get('http://www.google.com');console.log(result);复制代码
代理缓存
/* 反向代理* 负载均衡* 保护内部信息*/let sum = (function (n) { let cache = {}; function multi(n) { if (n <= 1) return 1; return n * cache[n - 1] || multi(n - 1); } return function () { let result = 0; for (let i = 1; i <= n; i++) { let res = multi(i); cache[i] = res; result += res; } return result; }})()console.time('cost')console.log(sum(10000))console.timeEnd('cost')复制代码
es6 Proxy
let wangyan = { name: 'wangyan', age: 30, height: 165,};let wangmama = new Proxy(wangyan, { get(target, key) { if (key === 'age') { return target.age - 2; } else if (key === 'height') { return target.height + 3; } else { return target[key]; } }, set(target, key, value) { if (key === 'bf') { let bf = value; if (bf.age > 40) { throw new Error('too old') } else if (bf.height < 175) { throw new Error('too low') } else { target.bf = bf; } } }});console.log(wangmama.age)console.log(wangmama.bf = { age: 50})复制代码