Section 5.1. About Static Objects


5.1. About Static Objects

Unlike the heavily object-oriented Java language, there is little of the traditional object-oriented vernacular in the object-based JavaScript language. As a result, scripters tend not to think in terms of static objects and object instantiation. But some of that does take place behind the scenes.

Some core language objects act as though they are true static objects. The Math object is a good example; it contains a number of properties and methods that scripts use without ever having to peel off an instance of that object to do some math.

In contrast, the Date object is a static object that generates an instance of itself each time someone creates a new date:

 var now = new Date( ); 

In this example, the now variable is an instance of the Date objecta snapshot of the object frozen in time. That instance provides access to many methods that let scripts get pieces of date and time, as well as set new values to those pieces. The methods actually live in the static object, but you access them through the instance that holds a value that can be influenced by those methods (yes, these methods are inherited, but JavaScript doesn't use this term much). Only on rare occasions do scripts ever need to look directly at the static Date object for other kinds of assistance (such as the UTC( ) method).

Most objects are either all static (Math) or completely suppress themselves from the scene once you create instances you work with (Object, Array, Number). Only a few objects operate in both modes, depending on whether you need the data of an instance of the object or one of the static properties or methods. You've seen how the Date object performs double duty. The RegExp object also performs this double duty; a regular expression instance object is created for you when you execute a related method. At the same time, you can access static objects (such as String and Array) to modify their basic behavior by assigning new properties and methods to their prototype (via the prototype property). New instances of such modified objects inherit the new properties or methods assigned to the prototype.




Dynamic HTML. The Definitive Reference
Dynamic HTML: The Definitive Reference
ISBN: 0596527403
EAN: 2147483647
Year: 2004
Pages: 120
Authors: Danny Goodman

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net