OldTroll
OldTroll

Reputation: 771

How to inspect variable in an anonymous function?

Say I have a code block that looks something like this...

$(function(){
    var Foo = "Thing";
    var Bar = "Other Thing";
    var Bag = new Widget({name: "Some Thing", color: "Purple"});
});

Is there a way to inspect or retrieve those variables/objects in the Chrome Console? I guess I'm probably trying to use the Chrome Console as too much of a REPL, but I'm curious as to if it's possible.

--Edit: Sorry, I should have included more information. I know I could add breakpoints or include a debugger call. I'm more interested in seeing the variables/object after everything has ran to completion.

Upvotes: 3

Views: 1750

Answers (2)

ErikE
ErikE

Reputation: 50271

The variables are scoped to the function, which means they cannot be accessed outside it unless they are explicitly passed out. Here are some options I can think of:

  1. You could declare variables of the same name in an outer scope, such as the window. Be careful, because if those variable names are used in other functions, they will all use the same "global" copy now and everything could break.

  2. You could add a "variable-collector" statement just before the final return of an anonymous function:

    var collector = [];
    
    $(function () {
       var Foo = "Thing",
          Bar = "Other Thing",
          Bag = new Widget({name: "Some Thing", color: "Purple"});
       collector.push({"anonymousfunction1": {Foo: Foo, Bar: Bar, Bag: Bag}});
       return something;
    });
    

    Then at the end of execution, you can inspect everything in the collector variable all you like. I made collector an array since I figured you might have multiple anonymous functions you want to learn about, or the function could be called multiple times (though it looks to me like a jQuery ready event, you never know).

  3. Just log the values to the console. This works in Chrome and Firefox (press F12) and may work in later versions of IE:

    $(function () {
       var Foo = "Thing",
          Bar = "Other Thing",
          Bag = new Widget({name: "Some Thing", color: "Purple"});
       console.log("Foo", Foo, "Bar", Bar, "Bag", Bag);
       return something;
    });
    

Upvotes: 1

Michael Johann
Michael Johann

Reputation: 475

I think it is not possible because those vars are local to the anonymous function.

You could temporarily do the following to inspect the values inside the function:

var Foo;    

$(function(){
    Foo = "Thing";
    var Bar = "Other Thing";
    var Bag = new Widget({name: "Some Thing", color: "Purple});
});

From here you can access Foo and see what value is inside.

Upvotes: 2

Related Questions