1

I need to trace the code that changes the property of an object. Breakpoints in Google Chrome DevTools are set upon line numbers; but in this particular scenario I don't know the code that manipulates the object in application flow, hence can't apply watch expressions over lines.

Is there a way that I can watch a variable in application scope regardless of lines of code?

Please not that I need to find the location in source code where an objects property gets changed not "when" or "what" a change applied.

abdul-wahab
  • 2,182
  • 3
  • 21
  • 35
  • possible duplicate of [Is there a way to "watch" a variable in google chrome?](http://stackoverflow.com/questions/22978549/is-there-a-way-to-watch-a-variable-in-google-chrome) – sdabet Aug 24 '15 at 14:38
  • Are you looking to get a stack trace as well? – soren468 Aug 24 '15 at 14:40
  • Nope, just need a way to find the piece of code that unwillingly modifies an object. Better if I can find it without injecting debugging code in application. I expected Google Chrome to have this functionality as it seems a basic debugging feature. – abdul-wahab Aug 24 '15 at 14:52

2 Answers2

2

The Object.prototype.watch() provides a way to have a callback function executed when a property of an object changes.

From the MDN documentation:

var o = { p: 1 };

o.watch('p', function (id, oldval, newval) {
  console.log('o.' + id + ' changed from ' + oldval + ' to ' + newval);
  return newval;
});

o.p = 2;
o.p = 3;
delete o.p;
o.p = 4;

o.unwatch('p');
o.p = 5;

outputs:

o.p changed from 1 to 2
o.p changed from 2 to 3
o.p changed from undefined to 4

Also, ECMAScript 7 will provide a more advanced Object.observe() function: see https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Object/observe

sdabet
  • 18,360
  • 11
  • 89
  • 158
1

You can define property accessor functions and set breakpoints in them. See defineSetter for more details.

var o = {};
Object.defineProperty(o, 'value', {
  set: function(val) {
    this._value = val;
    console.log(val);
  }
});
o.value = 5;
Yury Semikhatsky
  • 2,144
  • 13
  • 12