From 5f0a306976b8e0421c2ad5bcbe05da43da097923 Mon Sep 17 00:00:00 2001 From: dp~ <457509824@qq.com> Date: Thu, 26 Oct 2017 20:52:38 +0800 Subject: [PATCH] Proxy --- 20.proxy.md | 42 ++++++++++++++++++++++++++++++++++++++++++ README.MD | 3 ++- 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 20.proxy.md diff --git a/20.proxy.md b/20.proxy.md new file mode 100644 index 0000000..fa1cf4f --- /dev/null +++ b/20.proxy.md @@ -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" +``` \ No newline at end of file diff --git a/README.MD b/README.MD index 692b8ae..95a095c 100644 --- a/README.MD +++ b/README.MD @@ -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) \ No newline at end of file +* [生成器](https://github.com/dptms/es6/blob/master/19.generator.md) +* [Proxy](https://github.com/dptms/es6/blob/master/20.proxy.md) \ No newline at end of file