Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quick way to globalise a lot of variables in JavaScript?

I need to do a bit of quick testing with my code (getting the value of some variables inside a function), and I want to globalise them, so I can access them through the console.

I know this method:

function foo() {
  var foo = 'foo';
  window.foo = foo; // Make foo global
}

But what if I had something like this:

function foo() {
  var foo1 = 'foo';
  var foo2 = 'foo';
  var foo3 = 'foo';
  var foo4 = 'foo';
  var foo5 = 'foo';
  var foo6 = 'foo';
  var foo7 = 'foo';
  var foo8 = 'foo';
}

What would be a quicker way to globalise all those variables, without going window.foo1 = foo1, window.foo2 = foo2, etc.?

I don't wish this to be a code golf question, just a normal programming question.

like image 592
Lucas Avatar asked Jan 15 '13 03:01

Lucas


2 Answers

I don't think there's a way to do this. See this:

Access all local variables

Have you tried simply debugging in the console? With Chrome, you can set a breakpoint and then inspect all values. Check out this tutorial:

https://developers.google.com/chrome-developer-tools/docs/scripts-breakpoints

like image 60
Josh Rieken Avatar answered Sep 23 '22 03:09

Josh Rieken


Why not a single globals object instead of a bunch of variables?

function foo() {
    window.globals = {
        foo1 = 'foo',
        foo2 = 'foo',
        foo3 = 'foo',
        foo4 = 'foo',
        foo5 = 'foo',
        foo6 = 'foo',
        foo7 = 'foo',
        foo8 = 'foo'
    };
} 
like image 35
bfavaretto Avatar answered Sep 22 '22 03:09

bfavaretto