Object.defineProperty

 let data = {
            prop1: "属性1",
            prop2: {
                name: '属性2'
            }
        }

        function observe(obj) {
            if (!obj || Object.prototype.toString.call(obj) !== '[object Object]') return
            Object.keys(obj).forEach((key) => {
                this.defineProperty(obj, key, obj[key])
            })
        }

        // 不能用obj[key]的原因是:获取了值就会无限触发 get
        function defineProperty(obj, key, val) {
            Object.defineProperty(obj, key, {
                get() {
                    console.log('set', val);
                    return val
                },
                set(newVal) {
                    if (newVal === val) {
                        return
                    }
                    console.log('get', newVal);
                    val = newVal
                }
            })
        }
        observe(data)

        console.log(data.prop2);

        data.prop1 = 'prop1'
        data.prop2 = { name: 'prop2' }
        data.prop2

你可能感兴趣的:(Object.defineProperty)