Object.create方法的内部实现

Object.create方法的内部实现

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        var o = {
            name: "zs",
            age: 19
        };

        /* 01-基本使用 */
        /* Object.create(o) */
        /* 作用:创建一个空对象并且设置该对象的原型对象为第一个参数(o) */
        var n = Object.create(o);
        console.log(o);
        console.log(n, "n");

        var a = Object.create(Array.prototype);
        console.log(a);
        a.push(1, 2);

        // var f = Object.create(Function.prototype);
        // console.log(f);

        // var d = Object.create(Date.prototype);
        // console.log(d);


        /* 02-创建彻底的空对象 */
        /* 创建新的对象并且设置该对象的原型对象为null */
        var n1 = Object.create(null);
        console.log(n1);

        /* 03-思考: Object.create方法的内部实现 */
        Object.createNew = function(target) {
            // 内部核心实现
            // var o = new Object();
            // o.__proto__ = target;
            // return o;
        }

        // var n2 = Object.createNew(o);
        // console.log(n2, "n2");

        // var a2 = Object.createNew(Array.prototype);
        // console.log(a2);
        // a2.push(1, 2);


        /* 04-补充(了解) */
        /* Object.create(o,[options]) */
           /* var n3 = Object.create(o, {
            "className": {
                value: "1906",
            },
            "id": {
                value: "0001"
            }
        })
        console.log(n3);*/
        /* 默认使用上面方式创建出来的对象属性是不可以被枚举、不可以被修改、不可以被删除的 */

        var n3 = Object.create(o, {
            "className": {
                configurable: true,
                enumerable: true,
                value: "1906",
                writable: true
            },
            "id": {
                value: "0001"
            }
        })
        console.log(n3);
        console.log(n3.className, n3.id);
        for (var k in n3) {
            console.log(k, n3[k]);
        }

        n3.className = "1907";
        n3.id = "0002";
        console.log(n3.className, n3.id);
        delete n3.className;
        delete n3.id;
        console.log(n3);
    </script>
</body>

</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值