美文网首页
使用proxy实现immutable

使用proxy实现immutable

作者: 月_关 | 来源:发表于2020-08-28 18:05 被阅读0次

什么是immutable

如果需要频繁的操作一个复杂对象,每次完全拷贝一次的效率太低了。大部分场景下都只是更新了对象的一两个字段,其他字段都不变,对于这些不变的字段的拷贝都是多于的。

immutable就可以实现仅仅拷贝修改的值, 这样在React项目中,可以很好的优化性能

我们来用proxy实现一个简单按需拷贝


let obj = {
        a:1,
        c:{
            value:1
        }
    }

    class Store {
        constructor(state) {
            // 是否改动过数据
            this.modified = false;
            // 记录原对象
            this.source = state;
            // 记录改动的值
            this.copy = null;
        }

        get (key) {
            if (!this.modified) return this.source[key]
            return this.copy[key]
        }

        set (key, value) {
            if (!this.modified) this.modifing()
            return this.copy[key] = value
        }

        modifing () {
            if (this.modified) return
            this.modified = true
            this.copy = Array.isArray(this.source) ? this.source.slice() : {...this.source}
        }
    }

    const FLAG = 'FLAG'

    // 转发配置
    const handler = {
        get (target, key) {
            if (key === FLAG) return target
            return target.get(key)
        }, 

        set (target, key, value) {
            return target.set(key, value)
        }
    }

    function produce (state, producer) {
        const store = new Store(state)
        const proxy = new Proxy(store, handler)
        // 执行传入的回调方法
        producer(proxy)
        // 获取新的对象
        const newState = proxy[FLAG]
        // 查看对象是否改动
        if (newState.modified) return newState.copy
        return newState.source
    }

    let newObj = produce(obj, drat => {
        drat.a = {
            value:123
        }
    })

    console.log(newObj.c === obj.c) // true

相关文章

  • 使用proxy实现immutable

    什么是immutable 如果需要频繁的操作一个复杂对象,每次完全拷贝一次的效率太低了。大部分场景下都只是更新了对...

  • 【Immer】---Immer基本使用

    一、前言 Immer 是 mobx 的作者写的一个 immutable 库,核心实现是利用 ES6 的 proxy...

  • 原型继承

    // 使用Proxy实现propotypal inheritancefunction MultiPrototype...

  • vue.js设计与实现(阅读)-五(如何代理Object)

    理解proxy vue3是基于proxy代理实现的响应,那么什么事proxy代理,简单的说就是使用proxy可以实...

  • java 动态代理 jdk和cglib

    java中实现动态代理可以使用jdk提供的proxy实现,也可以通过cglib实现。二者主要的区别在于 proxy...

  • kubernetes ingress 部署

    我们可以使用kube-proxy实现service的负载均衡,但是使用kube-proxy方式有一定的局限,比如远...

  • 绑定代理proxy

    目的: 想要使用proxy代理方式,实现跨域访问,开发 官网方法: proxy 配置 webpack-dev-se...

  • jdk动态代理

    使用步骤创建接口及实现类实现代理处理器:实现 InvocationHandler ,实现 invoke(Proxy...

  • JAVA动态代理的实现原理

    java动态代理主要是有Proxy和InvocationHandler两个类实现的一、我先来看下如何使用Proxy...

  • immutable使用

    1. 使用groupBy之后,获取数据 使用groupBy将List转为以某个元素分组的“Map”之后,其实得到的...

网友评论

      本文标题:使用proxy实现immutable

      本文链接:https://www.haomeiwen.com/subject/uzzlsktx.html