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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

9 Comments

well, this is an object in(tro)spection, not exactly what i am asking for. but definitely useful for browser environment reflection.
Then what are you asking for?
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)
SLaks: .. my answer was meant rather on pure javascript, where is no window object. but your answer this is useful for browser env, thanks :)
If there is no window, you can use this in global scope.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.