问题
Similar to other questions here, like this one.
Is there a way to break on the change of a variable value in any JavaScript debugger? (like IE Developer tools, Visual Studio, or Firebug)?
I guess it\'s something like a \"watch variable\", but I want to be able to see the callstack and pause it when the change to the variable actually occurs.
An alternative approach might be to override the value setting with a custom setter, and put a breakpoint in that, but unfortunately that won\'t work for IE AFAIK.
UPDATE It appears that this type of behavior is available at least for unmanaged code written in C++ So I thought maybe a javascript engine written in C++ (Google\'s V8) might have something similar, but that doesn\'t appear to have what I want either.
回答1:
You don't even need an IDE - you can use "Object.watch()":
Object.Watch Tutorial
If you use any one debugger, I'd strongly recommend Firebug. For all your Javascript, HTML and CSS needs :-):
http://getfirebug.com/javascript
===========================================================
Update for 2019:
Object.Watch is Ancient History. Uncoincidentally, it's unavailable in most contemporary browsers.
My personal favorite JS debugging tool these days is Chrome Developer Tools.
My personal favorite JS IDE (for Angular, .Net Core, etc) is Microsoft Visual Studio Code (MSVC).
You can do just about any "expected" debugging operation - including set watches - with the Chrome debugger (just as you could with FF Firebug).
Chrome debugger is well integrated with the MSVC IDE.
Both are "free" (at least "free as in beer"); both run well on Windows, Mac and Linux.
回答2:
I'm having success with this library in Chrome and it looks to support all major browsers.
https://gist.github.com/eligrey/384583
Just include the .js file, then call:
yourObject.watch('someProperty', function() {
doWhatYouWant();
debugger;
console.write('this too');
alert('Object Changed'); //etc
});
回答3:
I don't know if I misunderstood your question. If you want to watch an expression and stop when it reaches a certain value while in a js debugging session in Chrome Developer Tools, it's rather trivial.
You can simply put a breakpoint on the line where the value you want to check is, then click with right mouse button on it and select "Edit breakpoint...". A dialog will pop up prompting for an expression, where execution will stop when its value its true.
For instance, let's say you have a loop and you are adding one unit to a variable inside it and want to stop execution when the variable equals to 3. The expression in loop would look like this:
n = i++;
You must set your breakpoint on that line and the expression to watch (after prompted by "Edit breakpoint...") would be n == 3
. When running your code it will stop there when your variable reaches that value.
You'll notice your condition is set because your breakpoint turns orange instead of blue.
来源:https://stackoverflow.com/questions/7910623/break-on-a-change-of-variable-value