-1

I have a variable foo which value changes from time to time. My code is huge, so I dont know where it is changed.

I want to know whether there is a possibility to know where the value of foo is manipulated. I don't care if i can solve it through the chrome debugger or via javascript code.

are there possibilities to do this?

InsOp
  • 2,425
  • 3
  • 27
  • 42
  • what about adding break points in your javascript console? this is a nice tutorial: https://developer.chrome.com/devtools/docs/javascript-debugging – Cacho Santa Sep 08 '15 at 16:55
  • thanks, but i did consider this option but it is too much of an argy-bargy – InsOp Sep 08 '15 at 17:00

3 Answers3

2

you can add an object.observe directly into chrome dev tools to get a console message when your property changes. Take a look at this: How to "break on property change" in chrome?

look for the answer that uses object.observe

Community
  • 1
  • 1
Chad McGrath
  • 1,561
  • 1
  • 11
  • 17
2

When you declare foo, you could do it like this:

Object.defineProperty(window, "foo", { 
    set: function (x) { this.value = x; console.trace() }, 
    get: function() { return this.value; }
});

Then, anytime foo is set it will run console.trace().

enter image description here

dave
  • 62,300
  • 5
  • 72
  • 93
1

As @ChadMcGrath pointed out Object.observe is probably what you want, but some other options are available, for example if a variable is a property on an object you could define a setter for it:

var o = {};
Object.defineProperty(o, "myProperty",{ 
  set: function (x) {
    console.log("Set myProperty to", x);
    console.trace();
    this.value = x; 
  },
  get: function () {
    return this.value;
  },
});

With ECMAScript 2015 you can use a Proxy, but this doesn't work in most browsers yet:

var handler = {
    set: function(target, name, value, receiver){
        console.log("Set", name, "to", value);
        console.trace();
        target[name] = value;
    }
};

var o = new Proxy({}, handler);
o.myProperty = 1; //Will console log and give you a trace.
Bjorn
  • 69,215
  • 39
  • 136
  • 164