Skip to content

Commit

Permalink
Proxy
Browse files Browse the repository at this point in the history
  • Loading branch information
dptms committed Oct 26, 2017
1 parent f8e197d commit 5f0a306
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
42 changes: 42 additions & 0 deletions 20.proxy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Proxy
> 通过 Proxy 你可以改写对象的一些默认的方法,定义自己的逻辑。有一种保护,预处理的感觉
```js
const person = { name: 'Dp', age: 2000 };
// `Proxy` 接收两个参数,第一个参数为要代理的目标对象,第二个参数是一个对象,包含我们要修改的方法
const personProxy = new Proxy(person, {
// 改变获取值的方式
get(target, key) {
return target[key].toLowerCase();
},
// 改变设置值的方式
set(target, key, value) {
target[key] = value.toUpperCase();
}
});
```

// 存取电话号码示例
```js
const phoneHandler = {
set(target, key, value) {
target[key] = value.match(/\d/g).join('');
},
get(target, key) {
return target[key].replace(/(\d{3})(\d{4})(\d{4})/, '$1-$2-$3');
}
}
const phoneProxy = new Proxy({}, phoneHandler);
```
打印结果
```
phoneProxy.home = '1350 8690 910'
"1350 8690 910"
phoneProxy.work = '18871233098'
"18871233098"
phoneProxy
Proxy {home: "13508690910", work: "18871233098"}
phoneProxy.home
"135-0869-0910"
phoneProxy.work
"188-7123-3098"
```
3 changes: 2 additions & 1 deletion README.MD
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,5 @@
* [模块](https://github.com/dptms/es6/blob/master/16.modules.md)
* [](https://github.com/dptms/es6/blob/master/17.classes.md)
* [遍历器 迭代器](https://github.com/dptms/es6/blob/master/18.iterator.md)
* [生成器](https://github.com/dptms/es6/blob/master/19.generator.md)
* [生成器](https://github.com/dptms/es6/blob/master/19.generator.md)
* [Proxy](https://github.com/dptms/es6/blob/master/20.proxy.md)

0 comments on commit 5f0a306

Please sign in to comment.