Forum Moderators: open
I was wondering if it is possible to get a list of all variables within the Javascript itself. Heh, kind of hard to explain, but it's quite simple what i want to do. Here's some pseudo code:
<html>
<script>
var blah = 5;
var hah = "test";
</script>
...
<script>
for (var x in <THIS PAGE>)
{
alert(x + " = " + this[x]);
}
</script>
</html>
RUN OUTPUT:
...
blah = 5
hah = test
...
I've already tried using "document" and "this" for <THIS PAGE> but they don't work. I mean it will alert certain variables that are inherent to those, but it will not alert "blah" or "hah".
Any help is appreciated.
Jason
Global variables are properties of the window (in a browser anyway). However, like some other properties they don't show up in a for..in loop.
There is an exception, though. If you really could be bothered, you could set your variables, not like this:
var a = 5 but instead like this:
window.a = 5 or, for functions..
window.functionName = function(){ ...blah...} Run this code:
<SCRIPT>// set A normally
var A = "hello, I'm A"
// check for A as explicit prop of window
alert(window.A) // or window["A"]
// set B as explicit prop of window
window.B = "hello, I'm B"
// check for var, B
alert(B)
// loop through window properties
// A doesn't show up
// but, B does (probably at the bottom)
var obj = window
var str = ""
for(var p in obj)
str += p + ": " + obj[p] + "\n"
alert(str)
</SCRIPT>
You were using this. That'll work too (self as well, I reckon)
I was kind of expecting a "no". I'm really just doing this for my own amusement anyway (I think JS is a pretty fun language to mess around with and make it do things it probably shouldn't :) ).
I've actually come up with another way of accomplishing this! Why not just parse it myself? Meaning: just go through document.documentElement.innerHTML and find all occurences of var. Haha, it'll take some time to write up the code, but it will definitely be fun (plus it makes me look like I'm doing work when I'm really not).
If anyone's interested, I'll post the code here once I'm done.
This will be treated as a variable declaration if the variable has never been used before:
foo = "bar"