<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>proxy</title> </head> <body> <h1>使用Proxy 和 Reflect 实现双向数据绑定</h1> <input type="text" id="input"> <h2>您输入的内容是: <i id="txt"></i></h2> <script> let input = document.querySelector('#input') let text = document.querySelector('#txt') //Proxy相当于拦截器,对于对象设置进行拦截 let newProxy = new Proxy({},{ //对获取对象属性进行拦截 get:(target,key,recevier)=>{ return Reflect.get(target,key,recevier) }, //对设置对象属性进行拦截 set:(target,key,value,receiver)=>{ if(key == 'text') text.innerHTML = value //实现双向数据绑定 return Reflect.set(target,key,value,receiver) } }) //监听输入事件,并绑定到对象中 //e.target是获取目标dom input.addEventListener('keyup',(e)=>{ newProxy.text = e.target.value }) </script> </body> </html>