views:

44

answers:

1

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?

+3  A: 

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
well, this is an object in(tro)spection, not exactly what i am asking for. but definitely useful for browser environment reflection.
mykhal
Then what are you asking for?
SLaks
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
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
If there is no `window`, you can use `this` in global scope.
SLaks
SLaks: `this` is it! thanks. could add this in your answer?
mykhal
i'm afrad `this` would interfere with jQuery behavior
mykhal
@mykhal: What do you mean?
SLaks
You can't iterate with `for..in` over the global scope in JScript (IE) can you?
Crescent Fresh
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
@mykhal: You can save a reference to the global `this` elsewhere, or you can put the loop in a separate function.
SLaks