Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Hongbusi opened this issue Jul 6, 2022 · 1 comment
Open

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

Hongbusi opened this issue Jul 6, 2022 · 1 comment
Labels
JS javascript

Comments

@Hongbusi
Copy link
Member

Hongbusi commented Jul 6, 2022

// 假设有一个 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 来定义也同样可以这样监听这个属性的变化。
@Hongbusi Hongbusi added today 每日一题。 JS javascript labels Jul 6, 2022
@myltx
Copy link

myltx commented Jul 6, 2022

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
    }
});

@Hongbusi Hongbusi removed the today 每日一题。 label Jul 7, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JS javascript
Development

No branches or pull requests

2 participants