-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
44 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters