0

I want to get "a, b" in this example https://jsfiddle.net/8dw9e5k7/ instead I get something else. Is it possible ?

    function test() {

        a = 5;
        b = 10;
        try {
          var variables = ""
          for (var name in this)
          variables += name + "\n";
          alert(variables);
        } catch(e) {
          alert(e.message)
        }
        
    }

    test();
user310291
  • 36,946
  • 82
  • 271
  • 487
  • it is not possible to get the used variables of the actual function uless you take the function as string and parse it. btw, why using `this` with global variables? – Nina Scholz May 25 '21 at 17:11
  • 1
    if necessary you can put your variables inside an object of your function – Mister Jojo May 25 '21 at 17:15

1 Answers1

2

Assigning non-existent variables in a function makes the variables global which means attached to the window object. That's why your code works somewhat and displays the variables along with many other things, because this refers to window.

Dumping your own variables attached to window is not possible in a clean way (some hacks still exist which consist in creating a fresh window with an iframe and compare it to the current window, check this answer if you're interested)

Now if you're expecting this to refer to the lexical scope of the current function, it's not the case and you can't retrieve it programmatically at all.

Guerric P
  • 30,447
  • 6
  • 48
  • 86