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 if they were 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
object—a 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 getTimezoneOffset()
method).
Most objects are either all static (Math
) or
completely suppress themselves from the scene once you create
instances you work with (String
,
Array
, Number
). Only a few ...
Get Dynamic HTML: The Definitive Reference now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.