Debugging closures in javascript

徘徊边缘 提交于 2019-12-10 04:57:22

问题


When I try to debug the javascript code which has a lot of closures I use to put a breakpoints.

Then I go to see the stack but most of the times I just see a call stack full of anonymous functions which is a nightmare for me.

What is the best way to debug closure in javascript?


回答1:


Well, in Google Chrome, you can see variables content throughout closures:

Local is the current execution context
Closure is its enclosing execution context
...
Up to the global execution context




回答2:


You can add a name to the callback function. That way the function name will be shown during debugging.

As an example in jQuery

$('div').each( function divLoop() {
  ..
});

In OOP Javascript, it's common to call the function as the name of the method

MyClass.prototype.methodName = function methodName() { ... }



回答3:


Instead of providing anonymous functions as your callback, try declaring a function and use that instead.

http://jsfiddle.net/v9Fas/

This way you can debug inside of the callback function just like a normal function call.



来源:https://stackoverflow.com/questions/9379612/debugging-closures-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!