手写 shallowReadonly 与 readonly

//就是在set那里设置不改变原来的数据,直接return
        const readonlyHandler = {
          get (target, key) {
            if (key==='_is_readonly') return true
        
            return Reflect.get(target, key)
          },
        
          set () {
            console.warn('只读的, 不能修改')
            return true
          },
        
          deleteProperty () {
            console.warn('只读的, 不能删除')
            return true
          },
        }
        
        /* 
        自定义shallowReadonly
        */
        function shallowReadonly(obj) {
          return new Proxy(obj, readonlyHandler)
        }
        
        /* 
        自定义readonly
        */
        function readonly(target) {
          if (target && typeof target==='object') {
            if (target instanceof Array) { 
                // 应为数组里面可能有引用类型数据所以要便利
              target.forEach((item, index) => {
                target[index] = readonly(item)
              })
            } else { // 对象也如此
              Object.keys(target).forEach(key => {
                target[key] = readonly(target[key])
              })
            }
            const proxy = new Proxy(target, readonlyHandler)
        
            return proxy 
          }
        
          return target
        }
        
        /* 测试自定义readonly */
        /* 测试自定义shallowReadonly */
        const objReadOnly = readonly({
          a: {
            b: 1
          }
        })
        const objReadOnly2 = shallowReadonly({
          a: {
            b: 1
          }
        })
        
        objReadOnly.a = 1
        objReadOnly.a.b = 2
        objReadOnly2.a = 1
        objReadOnly2.a.b = 2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大鸡腿最好吃

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值