xinggevip

Es2015 proxy之set、deleteProperty、has
index.html<!DOCTYPE html> <html lang="en&qu...
扫描右侧二维码阅读全文
20
2019/06

Es2015 proxy之set、deleteProperty、has

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>

<body>

    <script>
        /*
            proxy 代理

        */
        let obj = new Proxy({},{
            // 设置属性拦截
            set(target, prop, value){
                // console.log(target, prop, value);
                if(prop == 'age'){
                    if(!Number.isInteger(value)){
                        throw new TypeError('年龄不是整数');
                    }
                    if(value < 18){
                        throw new RangeError('年龄小于18岁');
                    }
                    
                };

                target[prop] = value;  
            },
            // 删除属性拦截
            deleteProperty(target, prop){
                console.log(`你想要删除${prop}属性`);
                delete target[prop];
            },
            // 判断是否含有此属性拦截
            has(target, prop){
                console.log(`判断是否含有${prop}属性`);
                console.log(prop in target);
            }
        });
        // 设置拦截结果
        obj.name = 'Tom';
        obj.a = 123;
        obj.age = 20;
        console.log(obj.a);     // 123
        console.log(obj.age);   // 20

        console.log('============================================');

        // 删除拦截结果
        delete obj.name;        // 你想要删除name属性
        console.log(obj);       // Proxy {a: 123, age: 20}

        console.log('============================================');

        // 判断是否含有此属性
        'a' in obj;             // 判断是否含有a属性 true

    </script>
</body>

</html>
Last modification:June 20th, 2019 at 09:48 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment