介绍
- 使用者无权访问目标对象
- 中间加代理,通过代理做授权和控制
例子
演示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class RealImg { constructor(fileName) { this.fileName = fileName this.loadFromeDisk() } display() { console.log('display...' + this.fileName); } loadFromeDisk() { console.log('loadFromeDisk...'); } }
class ProxyImg { constructor(fileName) { this.realImg = new RealImg(fileName) } display() { this.realImg.display() } }
let client = new ProxyImg('1.png') client.display()
|
场景
网页事件代理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <body> <div id="app"> <a href="#">a1</a> <a href="#">a2</a> <a href="#">a3</a> <a href="#">a4</a> <a href="#">a5</a> </div> <button id="button"></button> <script> let div1 = document.getElementById('app') div1.addEventListener('click', function(e) { var target = e.target if (target.nodeName === 'A') { console.log(target.innerHTML); } }) </script> </body>
|
jQuery $.proxy
1 2 3 4 5 6 7 8 9 10
| $('#div1').click(function() { $(this).addClass('red') }) $('#div1').click(function() { setTimeout(function() { $(this).addClass('red') }, 1000) })
|
通常我们这样解决:
1 2 3 4 5 6 7 8
| $('#div1').click(function() { var _this = this setTimeout(function() { $(_this).addClass('red') }, 1000) })
|
虽说箭头函数也可以解决。但是总有不适合用箭头函数的情况,这时候推荐用 $.proxy 解决,这样就少定义一个变量。
1 2 3 4 5 6
| $('#div1').click(function() { setTimeout($.proxy(function() { $(this).addClass('red') }, this), 1000); })
|
ES6 proxy
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| let star = { name: '张XX', age: 25, phone: '13910733521' }
let agent = new Proxy(star, { get: function (target, key) { if (key === 'phone') { return '18611112222' } if (key === 'price') { return 120000 } return target[key] }, set: function (target, key, val) { if (key === 'customPrice') { if (val < 100000) { throw new Error('价格太低') } else { target[key] = val return true } } } })
console.log(agent.name) console.log(agent.age) console.log(agent.phone) console.log(agent.price)
agent.customPrice = 150000
console.log('customPrice', agent.customPrice)
|
设计原则验证
- 代理类和目标类分离,隔离开目标类和使用类
- 符合开放封闭原则