使用proxy實現(xiàn)immutable

什么是immutable

如果需要頻繁的操作一個復(fù)雜對象,每次完全拷貝一次的效率太低了。大部分場景下都只是更新了對象的一兩個字段,其他字段都不變,對于這些不變的字段的拷貝都是多于的。

immutable就可以實現(xiàn)僅僅拷貝修改的值, 這樣在React項目中,可以很好的優(yōu)化性能

我們來用proxy實現(xiàn)一個簡單按需拷貝


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

    class Store {
        constructor(state) {
            // 是否改動過數(shù)據(jù)
            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'

    // 轉(zhuǎn)發(fā)配置
    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)
        // 執(zhí)行傳入的回調(diào)方法
        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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容