jQuery in Action

JavaScript Object fundamentals
321
It could be even easier (as we'll see shortly), but this will do for now.
But what can we do with this new object? It seemingly contains nothing: no
information, no complex semantics, nothing. Our brand-new, shiny object doesn't
get interesting until we start adding things to it--things known as properties.
A.1.2 Properties of objects
Like their server-side counterparts, JavaScript objects can contain data and pos-
sess methods (well...sort of, but that's getting ahead of ourselves). Unlike those
server-side brethren, these elements aren't pre-declared for an object; we create
them dynamically as needed.
Take a look at the following code fragment:
var ride = new Object();
ride.make = 'Yamaha';
ride.model = 'V-Star Silverado 1100';
ride.year = 2005;
ride.purchased = new Date(2005,3,12);
We create a new
Object
instance and assign it to a variable named
ride
. We then
populate this variable with a number of properties of different types: two strings, a
number, and an instance of the
Date
type.
We don't need to declare these properties prior to assigning them; they come
into being merely by the act of our assigning a value to them. That's mighty pow-
erful juju that gives us a great deal of flexibility. But before we get too giddy, let's
remember that flexibility always comes with a price!
For example, let's say that in a subsequent part of the page, we want to change
the value of the purchase date:
ride.purchased = new Date(2005,2,1);
No problem...unless we make an inadvertent typo such as
ride.purcahsed = new Date(2005,2,1);
There's no compiler to warn us that we've made a mistake; a new property named
purcahsed
is cheerfully created on our behalf, leaving us to wonder later on why
the new date didn't take when we reference the correctly spelled property.
With great power comes great responsibility (where have we heard that
before?), so type carefully!
NOTE
JavaScript debuggers such as Firebug for Firefox can be lifesavers when
dealing with such issues. Because typos such as these frequently result in
no JavaScript errors, relying on JavaScript consoles or error dialog boxes
is usually less than effective.


Другие страницы

 
Cкачать книги бесплатно без регистрации в электронном виде (pdf, chm, txt).Вы можете читать книги онлайн на нашем сайте литературного портала книг.Большая подборка учебников, пособий, интересных книг.Электронные книги на английском языке скачать бесплатно без смс.