Skip to content

JS 监听对象属性的改变 #29

Open

Description

@Hongbusi
// 假设有一个 user 对象

// 1. 在 ES5 中可以通过 Object.defineProperty 来实现已有属性的监听
Object.defineProperty(user, 'name', {
  set: function (key, value) {
    
  }
})
// 缺点:如果 id 不在 user 对象中,则不能监听 id 的变化

// 2. 在 ES6 中可以通过 Proxy 来实现
const user = new Proxy({}, {
  set: function (target, key, value, receiver) {
        
  }
})
// 这样即使有属性在 user 中不存在,通过 user.id 来定义也同样可以这样监听这个属性的变化。

Activity

  1. myltx commented on Jul 6, 2022

    @myltx

    es5

    Object.defineProperty

        const obj = {};
        Object.defineProperty(obj, 'data', {
          get(){
            return data
          },
          set(newVal) {
             onsole.log('我改变了')
             data = newVal;
          },
        });
        
         var obj = {};
         
        Object.defineProperties(obj, {
            a: {
                configurable: true, //表示该属性描述符可以被改变(默认为false)
                get: function() {
                    console.log('get: ',a)
                    return a
                },
                set: function(newValue) {
                    a = newValue;
                    console.log('set: ',a)
                }
            },
            b: {
                configurable: true,
                get: function() {
                    console.log('get: ',b)
                    return b;
                },
                set: function(newValue) {
                    b = newValue;
                    console.log('set: ',b)
                }
            }
        })

    es6

    Proxy

    const newObj =  new Proxy({},{
        get: function(obj, prop) {
            return prop in obj ? obj[prop] : null;
        },
        set(newVal){
            console.log(newVal)
            console.log('我改变了')
            return true
        }
    });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    JSjavascript

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions