5

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
  • it depends completely on what the problem is...can you be more specific? Commented Feb 21, 2012 at 14:54

3 Answers 3

5

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() { ... }
Sign up to request clarification or add additional context in comments.

Comments

2

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

enter image description here

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.