Syntax Support for Objects

For … in …

Sometimes an Object's contents are unknown. If it were an Array it would be easy to discover the contents—just look at the length property of the array and start accessing elements starting at 0 (zero). It's not so easy for Objects because the properties of the Object aren't neatly ordered and their names can be arbitrary strings—millions to choose from. There has to be another mechanism.

The for… statement discussed earlier has a variant designed for this job. Its syntax is:

for ( variable in object-variable )
    statement or block

An example:

for ( prop in some_object )
{
    if ( typeof( some_object[prop] ) == "string" )
        document.write(" Property: " + prop + " has value: " + some_object[prop]);
}

This example steps through all the properties of the some_object variable (presumably containing an object) and displays only those properties containing strings.

Unfortunately, the for .. in statement is a trap for beginners. "Ordinary" properties are reported as you would expect, but some special properties never appear. This can be a source of confusion. Typical examples are methods of objects that are supplied by the host, not by the script writer. See the Reference Section.

With …

The point has been made that every variable is part of an object, which we might call the current context, the current object, or the current scope. Sometimes (usually for typing convenience) we might want to change the current scope. The with statement does this. Its syntax is:

with ( object )
    Statement or block

An example:

var unrealistically_long_name = new Object;
unrealistically_long_name.sole_property = new Object;
unrealistically_long_name.sole_property.first = "Ready";
unrealistically_long_name.sole_property.second = "Set";
unrealistically_long_name.sole_property.third = "Go";

with ( unrealistically_long_name.sole_property )
{
    document.write( first + ',' + second + ',' + third '!');    // Ready, Set, Go!
}

To display the three deepest level properties would take long lines of code like lines 3, 4 and 5, were it not for the use of with surrounding the line producing the output. Further work could be saved by putting the last three assignments inside the with statement as well.

You may be suspicious by now that document must be some kind of object in a web browser, and write() a method of that object. Absolutely correct.

© 1997 by Wrox Press. All rights reserved.