开发者

javascript reflection: get variables

开发者 https://www.devze.com 2023-01-05 14:19 出处:网络
how can be a collection of global and/or local varibl开发者_JAVA百科es be obtained in javascript?

how can be a collection of global and/or local varibl开发者_JAVA百科es 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消