user310291
user310291

Reputation: 38190

How to get variables names inside a javascript function

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();

Upvotes: 0

Views: 74

Answers (1)

Guerric P
Guerric P

Reputation: 31815

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.

Upvotes: 2

Related Questions