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
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!