Reflect
1.语言内部的方法,与对象关系不大,放到Reflect上
let obj = {color:'red'} Reflect.preventExtensions(obj) // Object.preventExtensions(obj) obj.num = 100 console.log(obj)
2.修改Object返回的结果,让其变得更合理
Object.defineProperties(obj,'color',{ value:'red',configurable:false}) // Object.defineProperties(obj,'color',{ value:'green',configurable:true}) // 报错,无法执行下面的程序 console.log(Reflect.defineProperties(obj,'color',{ value:'green',configurable:true})) // 返回false,继续执行下面的程序
3.让Object操作变成函数的行为
let obj = {color:'red'} console.log(Reflect.has(obj,'color')) // color in obj console.log(Reflect.delete(obj,'color')) // delete obj.color
4.Reflect方法和Proxy方法是一一对应的
let obj = {color:'red'} let proxy = new Proxy(obj,{ get(...args){ return Reflect.get(...args) }, set(...args){ return Reflect.set(...args) } }) proxy.color = 'red' console.log(obj)
5.Reflect-demo
// eg1:new对象 class Demo{ constructor(color) { this.color = color } } // 通过Reflect创建 Reflect.construct(Demo,['red']) // eg2:遍历元素 const divs = document.getElementsByTagName('div') Array.prototype.forEach.call(divs,item => console.log(item)) Reflect.apply(Array.prototype.forEach,divs,[item => console.log(item)])
6.Vue 数据绑定-proxy方式
let data = {} let proxy = new Proxy(data, { set(target,key,value,receiver){ // 更新数据 Reflect.set(target,key,value,receiver) // 更新视图 updateView(receiver) }
}) // 获取模板 let tpl = document.getElementsById('app').innerHTML; function updateView(data){ // 替换插值语法 let html = tpl.replace(/{{(\w+)}}/g,(match,$0 = '') => data[$0]) // 更新视图 document.getElementById('app').innerHTML = html } // 代理数据-更新视图 proxy.msg = '喵喵'