ES6 Proxy

171 阅读1分钟

1.什么是Proxy

Proxy 可以对目标对象的读取、函数调用等操作进行拦截,然后进行操作处理。它不直接操作对象,而是像代理模式,通过对象的代理对象进行操作,在进行这些操作时,可以添加一些需要的额外操作。它最终返回的是一个新的对象

2.使用

通过 Proxy 构造函数生成实例对象时,需要提供这两个参数。 target(目标对象)和handler(一个对象里面有set和get方法)

3.示例

<!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>
        <button onclick="getFun()">执行get方法</button>
        <button onclick="setFun()">执行set方法</button>
        <button onclick="seeValue()">查看当前对象值</button>
    </div>
</body>
<script>
    let targetObj = {
        name: "初始name",
        age: 25
    }
    console.log("初始对象值",targetObj)
    let handler = {
        get: function (target, key,value) {
            console.log('getting ' + key);
            console.log("proxy",proxy);
            return target[key];
        },
        set: function (target, key, value) {
            console.log('setting ' + key);
            target[key] = value;
        }
    }
    let proxy = new Proxy(targetObj, handler) //进行代理

    function getFun(params) {
        proxy.name     // 实际执行 handler.get
     
    }
    function setFun() {

        proxy.age = 16 // 实际执行 handler.set
     
    }
    function seeValue() {
         console.log(targetObj)
    }

</script>

</html>