I am newish to JavaScript and was playing around with it when I discovered that it’s possible to create variables with this syntax:
document.foo = 'bar'.
The advantage to it, from what I can tell, is that when I do something like:
if (document.foo)
do something;
the interpreter doesn’t throw an exception if the variable hasn’t been initiated yet.
What I don’t know, but would like to know, is what the term for creating a variable like this is called. Is it just global variable, or a member variable, or a new type. I’d also like to know if there is any reason I wouldn’t want to create a variable in this way.
So anyone looking to give out guru advice, it will be appreciated.
Short answer: the term is implicit declaration.
Slightly bloated answer: Although it’s perfectly legal to create variables that way there are some downsides when applied to object orientated programming and the ability to document your software.
If your objects have different structural configurations during run time the state of your software can get very hard to predict and maintaining the code gets harder and harder.
My advice would be: Use some kind of inheritance model or make use of javascripts prototypical architecture to declare (and set wise defaults!) ahead of time. This leads to easier documentation and also provides an opportunity to review your mental model of your software’s purpose.
A good intro to the application of JS inheritance is available from john resig here : http://ejohn.org/blog/simple-javascript-inheritance/