Object.watch() for all browsers?

前端 未结 8 777
囚心锁ツ
囚心锁ツ 2020-11-22 13:06

Please note that Object.Watch and Object.Observe are both deprecated now (as of Jun 2018).


I was looking for an easy way to monitor an object

8条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 13:28

    Current Answer

    Use the new Proxy object, which can watch changes to it's target.

    let validator = {
        set: function(obj, prop, value) {
            if (prop === 'age') {
                if (!Number.isInteger(value)) {
                    throw new TypeError('The age is not an integer');
                }
                if (value > 200) {
                    throw new RangeError('The age seems invalid');
                }
            }
    
            // The default behavior to store the value
            obj[prop] = value;
    
            // Indicate success
            return true;
        }
    };
    
    let person = new Proxy({}, validator);
    
    person.age = 100;
    console.log(person.age); // 100
    person.age = 'young'; // Throws an exception
    person.age = 300; // Throws an exception
    

    Old answer from 2015

    You could have used Object.observe() from ES7. Here's a polyfill. But Object.observe() is now cancelled. Sorry people!

提交回复
热议问题