Set breakpoint on Javascript object's property change
Data is the blood of a software application. Oftentimes, we need to know when and where a specific value is changed. That's easy for GDB in good old C world using hardware watchpoint. For Javascript, we can use setter/getter to catch the setting action.
function breakOnChange(obj, key) {
let value = obj[key];
Object.defineProperty(obj, key, {
set(newValue) {
value = newValue;
debugger;
},
get() {
return value;
}
});
};
let obj = {a: 1};
breakOnChange(obj, 'a');