ES6新内置对象Reflect和Proxy的基本使用
2023-02-18 16:30:14 时间
Reflect
为操作对象提供的新API
列举常用的API
const obj = {
name: 'swt',
age: 20
}
/*
* 属性写入
*/
Reflect.set(obj, 'sex', '男')
console.log(obj) // {name: "swt", age: 20, sex: "男"}
/*
* 属性读取
*/
const a = Reflect.get(obj, 'name')
console.log(a) // swt
/*
* 属性删除
*/
Reflect.deleteProperty(obj, 'sex')
console.log(obj) // {name: "swt", age: 20}
/*
* 属性包含
*/
const b = Reflect.has(obj, 'name')
console.log(b) // true
/*
* 属性遍历
*/
const c = Reflect.ownKeys(obj)
console.log(c) // ["name", "age", "sex"]
Proxy
对象属性读写
const person = {
name: 'cyw',
age: 20
}
const personProxy = new Proxy(person, {
get(obj, key) {
return key in obj ? obj[key] : 'default'
},
set(obj, key, value) {
if(key === 'age') {
if(!Number.isIntegr(value)) {
throw new TypeError(`${value} is not an int`)
}
}
obj[key] = value
}
})
personProxy.age = 10.5 // Uncaught TypeError: 10.5 is not an int
console.log(personProxy.name) // cyw
console.log(personProxy.sex) // default
监视数组操作
const list = []
const listProxy = new Proxy(list, {
set(obj, key, value) {
console.log('set', key, value)
obj[key] = value
return true
}
})
listProxy.push(100)
// set 0 100
// set length 1
相关文章
- 个人笔记(路由、网络相关)
- 个人笔记(vue篇)
- 怎么去水印不伤原图?这个去水印方法值得收藏!
- 羊了个羊,通关秘籍!
- 实用 | 盘点抓包修改响应结果的 2 种方式!
- 小技巧 | Chrome 插件如何完成剪切板的操作!
- DDOS攻击讲堂
- 思科交换机简单配置
- 实战 | 如何利用 Scrapy 编写一个完整的爬虫!
- 超简单就可做一款三功能的LED车灯
- 实战 | 教你快速爬取热门股票,辅助量化交易!
- 行业趋势|光伏行业SCM供应链数字化管理优势、价值
- 破除上下游梗阻,如何为能源化工行业开出“新良方”?
- 软件分享 | 第一期 Markdown神器Typora安装和破解教程
- jira-dev-tool插件安装失败的解决方法
- 软件分享 | 第二期 截图神器snipaste安装和使用教程
- 基于Hexo搭建静态博客
- 软件分享 | 第三期 搜索神器listary安装和使用
- 发送HTML模板邮件
- 使用3-hexo主题时无法正常渲染html代码