其他分享
首页 > 其他分享> > 年轻人,你搞定对象了吗?-2 -cyy

年轻人,你搞定对象了吗?-2 -cyy

作者:互联网

不允许向对象中添加属性API:

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

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <style>
        button {
            position: absolute;
        }
    </style>
</head>

<body>
    <script>
        'use strict'; // 严格模式下有报错提示,非严格模式直接无效
        // let obj = {
        //     name: 'cyy',
        //     age: 18
        // };
        // Object.preventExtensions(obj); //禁止添加属性
        // // obj.sex = 'girl';//会报错

        // // 判断对象的属性是否可以被添加或修改
        // if (Object.isExtensible(obj)) {
        //     obj.sex = 'girl'
        // }
        // console.log(obj);


        let obj = {
            name: 'cyy',
            age: 18
        };
        // 判断对象的属性是否可以被添加或修改
        if (Object.isExtensible(obj)) {
            obj.name = 'cyy2';
        }
        console.log(obj);

    </script>
</body>

</html>

 

封闭对象的API操作:

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

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <style>
        button {
            position: absolute;
        }
    </style>
</head>

<body>
    <script>
        'use strict'; // 严格模式下有报错提示,非严格模式直接无效
        let obj = {
            name: 'cyy',
            age: 18
        };
        console.log(JSON.stringify(Object.getOwnPropertyDescriptors(obj), null, 2));
        Object.seal(obj); //封闭对象
        //configurable属性从true变成了false,不能删除和配置属性
        console.log(JSON.stringify(Object.getOwnPropertyDescriptors(obj), null, 2));

        // 不能添加属性
        // obj.sex = 'girl';

        // 不能删除属性
        // delete obj.name;

        //判断对象是否被封闭
        console.log(Object.isSealed(obj));

        if (!Object.isSealed(obj)) {
            delete obj.name;
        }
    </script>
</body>

</html>

 

冻结对象API特性:

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

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <style>
        button {
            position: absolute;
        }
    </style>
</head>

<body>
    <script>
        'use strict'; // 严格模式下有报错提示,非严格模式直接无效
        let obj = {
            name: 'cyy',
            age: 18
        };
        console.log(JSON.stringify(Object.getOwnPropertyDescriptors(obj), null, 2));
        Object.freeze(obj); //封闭对象
        //configurable属性和writable属性从true变成了false,不能删除和配置属性
        console.log(JSON.stringify(Object.getOwnPropertyDescriptors(obj), null, 2));

        // 不能添加属性
        // obj.sex = 'girl';

        // 不能修改属性
        // obj.name = 'cyy2';

        // 不能删除属性
        // delete obj.name;

        //判断对象是否被冻结
        console.log(Object.isFrozen(obj));

        if (!Object.isFrozen(obj)) {
            obj.name = 'cyy2';
        }
    </script>
</body>

</html>

 

VUEJS数据绑定的容器更新:

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

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <style>

    </style>
</head>

<body>
    <input type="text" v-model="title">
    <input type="text" v-model="title">
    <div v-bind="title">这里也会发生更新</div>
    <hr>
    <input type="text" v-model="content">
    <div v-bind="content">这里也会发生更新</div>

    <script>
        'use strict';

        // 构造函数
        function View() {
            let proxy = new Proxy({}, {
                get(obj, property) {

                },
                set(obj, property, value) {
                    console.log(obj, property, value);
                    document.querySelectorAll(`[v-model="${property}"]`).forEach(item => {
                        item.value = value;
                    });
                    document.querySelectorAll(`[v-bind="${property}"]`).forEach(item => {
                        item.innerHTML = value;
                    });
                    return true;
                }
            });
            this.init = function () {
                const els = document.querySelectorAll('[v-model]');
                els.forEach(item => {
                    item.addEventListener('keyup', function () {
                        proxy[this.getAttribute('v-model')] = this.value;
                    });
                });
            }
        }
        new View().init();
    </script>
</body>

</html>

 

表单验证组件的代理工厂:

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

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <style>
        .error {
            border: 10px solid red;
        }
    </style>
</head>

<body>
    <input type="text" rule="max:12,min:3" validate>
    <input type="text" rule="max:3,isNumber" validate>

    <script>
        'use strict';

        class Validate {
            max(value, len) {
                return value.length <= len;
            }
            min(value, len) {
                return value.length >= len;
            }
            isNumber(value) {
                return /^\d+$/.test(value);
            }
        }
        // let v = new Validate();
        // console.log(v.max('abc', 4));
        // console.log(v.min('abc', 4));
        // console.log(v.isNumber('abc'));
        // console.log(v.isNumber(22));

        // 代理工厂
        function ProxyFactory(target) {
            return new Proxy(target, {
                get(target, key) {
                    return target[key];
                },
                set(target, key, el) {
                    // console.log(target, key, el);
                    const rule = el.getAttribute('rule');
                    const validate = new Validate();

                    let state = rule.split(',').every(rule => {
                        const info = rule.split(':');
                        return validate[info[0]](el.value, info[1]);
                    });
                    el.classList[state ? 'remove' : 'add']('error');
                    return true;
                }
            });
        }
        const proxy = new ProxyFactory(document.querySelectorAll('[validate]'));
        proxy.forEach((item, i) => {
            item.addEventListener('keyup', function () {
                // console.log(item, i);
                proxy[i] = this;
            })
        })
    </script>
</body>

</html>

 

JSON数据解决什么问题:

        'use strict';

        // xml 结构复杂,过于麻烦
        // 现在主要用json
        // let data = {
        //     name: 'cyy',
        //     arr: [
        //         1, 2, 3, 4
        //     ]
        // };
        // //js对象转json
        // console.log(JSON.stringify(data));
        // console.log(JSON.stringify(data, null, 2));
        // // json是字符串类型
        // console.log(typeof JSON.stringify(data));


        let phpJson = `{"name":"\u540e\u76fe\u4eba","url":"hdcms.com"}`;
        // json转js对象
        let obj = JSON.parse(phpJson);
        console.log(obj);
        console.log(obj.name);
    </script>

 

JSON序列化与自定义toJSON:

    <script>
        'use strict';

        // let data = {
        //     name: 'cyy',
        //     arr: [
        //         1, 2, 3, 4
        //     ]
        // };
        // //stringify字符串化
        // // 第二个参数:要保留的字段,设置为null代表全部
        // // 第三个参数:tab位
        // console.log(JSON.stringify(data, ['name'], 4));


        // let arr = [11, 22, 33];
        // console.log(JSON.stringify(arr, null, 2));


        let data = {
            name: 'cyy',
            arr: [
                1, 2, 3, 4
            ],
            toJSON() {
                return {
                    name: this.name + "小可爱"
                }
            }
        };
        console.log(JSON.stringify(data));
    </script>

 

JSON转为JS可操作类型:

    <script>
        'use strict';

        let data = {
            name: 'cyy',
            arr: [
                1, 2, 3, 4
            ]
        };
        let json = JSON.stringify(data, null, 2);

        // let obj = JSON.parse(json);
        // console.log(obj);

        let obj = JSON.parse(json, (key, value) => {
            if (key == 'name') {
                value = '我是-' + value;
            }
            return value;
        });
        console.log(obj);

    </script>

 

标签:搞定,obj,log,cyy,年轻人,JSON,let,console,name
来源: https://www.cnblogs.com/chenyingying0/p/14015969.html