4

how can be a collection of global and/or local varibles be obtained in javascript?

(like e.g. in Python by globals() or locals())

if there is no such functionality available in javascript, how do some javascript console interfaces obtain them, to be able to autocomplete?

mykhal
  • 19,175
  • 11
  • 72
  • 80
  • here i have found pretty similar question: http://stackoverflow.com/questions/3831932/access-all-local-variables – mykhal Aug 03 '11 at 19:50

1 Answers1

4

You're looking for the for / in loop.

To get all globals:

for(var name in this) {
    var value = this[name];
    //Do things
}

(This will only work correctly when run in global scope; you can wrap it in an anonymous function to ensure that. However, beware of with blocks)

To get all properties of a particular object:

for(var name in obj) {
    //Optionally:
    if (!obj.hasOwnProperty(name)) continue;    //Skip inherited properties

    var value = obj[name];
    //Do things
}

However, there is no way to loop through all local variables.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • well, this is an object in(tro)spection, not exactly what i am asking for. but definitely useful for browser environment reflection. – mykhal Jul 05 '10 at 14:06
  • Then what are you asking for? – SLaks Jul 05 '10 at 14:16
  • SLaks: you note that it's not possible would be sufficient, if it's the case (it was not already there in time of writing my previuos comment) – mykhal Jul 05 '10 at 14:20
  • SLaks: .. my answer was meant rather on pure javascript, where is no `window` object. but your answer this is useful for browser env, thanks :) – mykhal Jul 05 '10 at 14:30
  • 2
    If there is no `window`, you can use `this` in global scope. – SLaks Jul 05 '10 at 14:33
  • i'm afrad `this` would interfere with jQuery behavior – mykhal Jul 05 '10 at 15:05
  • You can't iterate with `for..in` over the global scope in JScript (IE) can you? – Crescent Fresh Jul 05 '10 at 17:54
  • SLaks: unfortunately, `this` seems to be redefined by jQuery's event mechanism, so such an introspection, using `this` does not work inside user-bound jQuery's event functions. but it's a different problem.. – mykhal Jul 05 '10 at 17:55
  • @mykhal: You can save a reference to the global `this` elsewhere, or you can put the loop in a separate function. – SLaks Jul 05 '10 at 22:19