以编程方式控制 Javascript 中的断点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5271465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:35:58  来源:igfitidea点击:

Programmatically control breakpoints in Javascript?

javascriptdebuggingbreakpoints

提问by nickf

Is it possible, in any browser, using any plugin, to enable or disable breakpoints in your code programmatically?

是否可以在任何浏览器中使用任何插件以编程方式启用或禁用代码中的断点?

I already know about setting conditional breakpoints, but I'm really interested in setting them via code.

我已经知道设置条件断点,但我对通过代码设置它们真的很感兴趣。

回答by Marcus Pope

First you could add a call to a function like __checkDebug(); which will check for a global (or semi-global) variable and when said variable is true, call debugger.

首先,您可以添加对 __checkDebug() 之类的函数的调用;这将检查全局(或半全局)变量,当所述变量为真时,调用调试器。

  
function __checkDebug() {
   if (debugme) debugger;
}

all of your functions you're concerned about debugging would be like so:

您关心的所有调试功能都是这样的:

  
function foo() {
   __checkDebug();

   //.... whatever foo was gonna do.
}

You can then take it a little further and dynamically decorate functions while the code is being executed like so:

然后,您可以更进一步,并在执行代码时动态装饰函数,如下所示:


Function.prototype.debug = function(){   
   var fn = this; 
   return function(){     
       if (debugme) debugger; 
       return fn.apply(this, arguments);     
   }; 
}; 

foo = foo.debug();  

now any time foo is called it will call debugger if the debugme variable is truthy.

现在,无论何时调用 foo,如果 debugme 变量为真,它都会调用调试器。

Another option would be to build a javascript build system that injects the call after every function declaration - this requires a syntax parser but if you're only looking to modify functions a simple tokenizer for that use case is pretty easy to write - but I'll leave that up to you.

另一种选择是构建一个 javascript 构建系统,在每个函数声明之后注入调用——这需要一个语法解析器,但如果你只想修改函数,那么为该用例编写一个简单的标记器非常容易——但我就交给你了。

回答by CoolEsh

You can use debugger;in code to make breakpoint for firebug. For example:

您可以debugger;在代码中使用为萤火虫制作断点。例如:

alert('1');
debugger;
alert('2');

And firebug automatically stops on this keyword.

firebug 会自动停止在这个关键字上。

回答by Tramov

Have a look at the FireBug functions debug(fn) & undebug(fn) names which set a breakpoint on the first line of the named function.

查看 FireBug 函数debug(fn) 和undebug(fn) 名称,它们在命名函数的第一行设置断点。

See point #6:

见第 6 点:

http://michaelsync.net/2007/09/30/firebug-tutorial-script-tab-javascript-debugging

http://michaelsync.net/2007/09/30/firebug-tutorial-script-tab-javascript-debugging