Proxy实现数据双向绑定

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="content"></div>

  <script>
    const content = document.getElementById('content')
    const info = {
      name: 'zz',
      age: 18
    }
    const i1 = new Proxy(info, {
      get(target, property, receiver) {
        return info[property]
      },
      set(target, property, value, receiver) {
        info[property]= value
        content.innerText = value
      }
    })
    i1.name = 'yy'
    console.log('i1', info, i1)
  </script>
</body>
</html>

  1. proxy是一个实例,接受两个参数,一个是当前要修改的对象(info),一个是修改对象的和获取对象的方法(get和set)
  2. get接受三个参数,set接受四个参数,property代表要修改的属性名
  3. 修改i1和info属性都能实现数据的双向绑定

Proxy实现数据双向绑定_第1张图片

/* ES Module 和 Common JS */
    /*
    * ES Module通常是浏览器环境运行
      export default {
        a: 1,
        b: 2
      }
      export const a = 1
      export const fn () {}

      import {a, fun} from 'xxx'
      import AModule from 'xxx'
    * Common JS(nodejs环境运行)
      module.exports = {
        a: 1,
        b: 2
      }
      exports.a = 1
      const AModule = require('xxx')
    */

你可能感兴趣的:(javascript,前端,开发语言)