本文介绍了Chrome JavaScript调试:当值更改时如何中断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在调试一个大的JavaScript代码库,在某些时候,刷新页面时,控制台变量将变为空。

I am debugging a large JavaScript code base where, at some point, the "console" variable gets nulled when refreshing the page.

有没有办法设置控制台上的一个手表,当该值发生变化时(或当条件(console == null)为true)时,JavaScript执行失败?

Is there a way to set a watch on console and make JavaScript break execution when that value changes (or when a condition (console == null) is true)?

我在Windows 7上使用Chrome。

I am using Chrome on Windows 7.

推荐答案

以下答案不适用于 window.console 因为控制台(像其他浏览器本机的环境变量)被特别处理。任何将价值分配给 console 的尝试只会覆盖原始值;它不会取代它。您不能检测控制台值何时更改,但您可以删除window.console 恢复原始环境 - 提供的价值。

The answer below doesn't work for window.console because console (like other browser-native environment variables) is treated specially. Any attempt to assign a value to console only "covers up" the original value; it does not replace it. You can't detect when the console value changes, but you can delete window.console to restore the original environment-supplied value.

对于其他值,请使用为一些全局 window.foobar 。每当 window.foobar 分配一个新值时,setter函数运行:

For other values, use Object.defineProperty to define a custom setter for some global window.foobar. The setter function runs whenever window.foobar is assigned a new value:

(function() {
    var actualFoobar = window.foobar;

    Object.defineProperty(window, "foobar", {
        set: function(newValue) {
            if(newValue === null) {
                alert("someone is clobbering foobar!"); // <-- breakpoint here!
            }

            // comment out to disallow setting window.foobar
            actualFoobar = newValue;
        },

        get: function() { return actualFoobar; }
    });

})();

然后,在该setter函数中放置一个断点。

Then, put a breakpoint in that setter function.

此方法适用于全局变量或任何对象属性(只需将窗口更改为具有该属性的对象)。

This approach will work for global variables or any object property (simply change window to the object that has the property).

这篇关于Chrome JavaScript调试:当值更改时如何中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 07:22