5 The property fallIn is assigned an anonymous function that will serve as a method for this object.. 6 The property fallOut is assigned an anonymous function that will server as anoth
Trang 18.3 Object Literals
Object literals enable you to create objects that support many features without directly
invoking a function When a function acts as constructor you have to keep track of the
order of arguments that will be passed, and so on Not so with object literals They are
similar to hashes in other languages using key/value pairs to represent fields The fields
can be nested The basic syntax for an object literal is:
1 A colon separates the property name from its value
2 A comma separates each set of name/value pairs from the next set
3 The comma should be omitted from the last name/value pair.1
Even with nested key/value pairs, the last key/value pair does not have a comma
4 The entire object is enclosed in curly braces
The value assigned to a property can be of any data type, including array literals and
object literals (arrays are covered in Chapter 9) Using the new operator with the
Object() constructor or an object literal is both simple and logical, but the biggest
short-coming is that the code is not reusable; that is, you would have to retype the code to use
it again within the program, whereas you can use a constructor function to create
mul-tiple instances of an object In Example 8.7, one soldier object is created as an object
literal, but we cannot create two soldier objects unless we redefine another entirely new
object (See JSON in Chapter 18, “An Introduction to Ajax (with JSON),” for a good
rea-son to use object literals.)
Figure 8.7 Two objects of the Distance class call the calculate() method.
1 Firefox will not complain if the last field is terminated with a comma; Internet Explorer will raise an
exception.
Trang 2In the next example, two methods are created for the object literal Once an object
literal has been defined you can later add more properties to it as demonstrated in
Example 8.7
F O RM A T
var object = { property1: value, property2: value };
E X A M P L E
var area = { length: 15, width: 5 };
E X A M P L E 8 7
<html>
<head><title>working with literal objects</title>
<script type="text/javascript">
1 var soldier = {
3 rank: "captain",
4 picture: "keeweeboy.jpg",
5 fallIn: function() {
alert("At attention, arms at the side, head and
eyes forward.");
},
6 fallOut: function() {
alert("Drop out of formation, step back, about face!");
} };
</script>
</head>
<body>
<big>
<script type="text/javascript">
7 soldier.name="Tina Savage"; // Assign value to object
// property
8 document.write("The soldier's name is ",
soldier.name,".<br />");
document.write(soldier.name+"'s rank is ",
soldier.rank+."<br />”);
9 document.write("<img src='"+soldier.picture+"'>")
10 soldier.fallIn(); //call object’s methods
11 soldier.fallOut();
</script>
</big>
</body>
</html>
Trang 3E X P L A N A T I O N
1 A literal object called soldier is defined with properties and methods.
2 The property name is separated from its value with a colon The value is undefined
at this point
3 The property is rank Its value is a string, “captain”.
4 This property is picture; its value is a JPEG file.
5 The property fallIn is assigned an anonymous function that will serve as a method
for this object
6 The property fallOut is assigned an anonymous function that will server as
anoth-er method for this object
7 The object’s property name is assigned a value, “Tina Savage” It is initially assigned
“undefined”
8 In this and the next line the value of the name and rank properties is printed.
9 A picture of the soldier is assigned to the img tag’s src property and displayed in
the document
10 The method for the object, fallIn(), is called Note that by appending the ()
oper-ator to the fallIn property, the function assigned to it on line 5 is called and
exe-cuted
11 The method for the object, fallOut(), is called By appending the () operator to the
fallOut property, the function assigned to it on line 6 is called and executed The
output is shown in Figure 8.8
Figure 8.8 A literal object with properties and methods.
Trang 4E X A M P L E 8 8
<html>
<head><title>Object Literals</title>
<script type = "text/javascript">
1 var Car = { // Create a Car object
year:2006, price:undefined,
name:"Henry Lee", cell_phone: "222-222-2222",
4 address:{street: "10 Main",
city: "SF", state: "CA"
} }, dealer: "SF Honda",
5 display: function() {details="Make: "+Car.make+"\n";
details += "Year: "+Car.year+"\n";
details += "Price: $"+Car.price+"\n";
details += "Owner: "+
Car.owner.name+"\n";
alert(details);
} };
</script>
</head>
<body>
<script type="text/javascript">
6 Car.make="Honda Civic"; // Assign value
7 Car.year=2009; // Update the year
8 Car.price=30000;
</script>
</body>
</html>
E X P L A N A T I O N
1 An object literal Car is created and initialized
2 The properties for the Car object are assigned Properties are separated from their
corresponding values with a colon and each property/value pair is separated by a
comma, except the last one Watch the commas Internet Explorer is very
partic-ular about this rule
3 The owner property contains another set of property/value pairs The value of the
owner property is another nested object literal with key/value pairs enclosed in
curly braces
Trang 5The with keyword is used as a kind of shorthand for referencing an object’s properties or
methods The object specified as an argument to with becomes the current object for the
duration of the block that follows The properties and methods for the object can be
used without naming the object or using the dot syntax A caveat: This shorthand
might save typing, but it will also take a lot longer to run because JavaScript checks
each variable within the with block to see whether or not it is a property of the object
it references
4 The owner has an address field that contains its set of property/value pairs
5 This property will act as the object’s method It is assigned an inline function
de-fined to display properties of the object
6 With object literals there is no constructor function This line assigns a value to
an undefined Car property called make.
7 This Car’s year property is assigned a new value
8 The Car object’s price property, originally undefined, is assigned a value
9 The Car object’s method called details() is called to display the properties of the
object Be sure to observe the syntax differences; that is, an equals sign rather than
colon between property and value, and an optional semicolon rather than comma
at the end of the assignment The output is shown in Figure 8.9
Figure 8.9 Nesting property/value pairs in an object literal Output of Example 8.8
literal objects.
E X P L A N A T I O N (C O N T I N U E D)
Trang 6F O RM A T
with (object){
< properties used without the object name and dot>
}
E X A M P L E
with(employee){
document.write(name, ssn, address);
}
E X A M P L E 8 9
<html>
<head><title>The with Keyword</title>
<script type = "text/javascript">
1 function book(title, author, publisher){
this.author = author;
this.publisher = publisher;
3 this.show = show; // Define a method
}
4 function show(){
5 with(this){ // The with keyword with this
6 var info = "The title is " + title;
info += "\nThe author is " + author;
info += "\nThe publisher is " + publisher;
} }
</script>
</head>
<body bgcolor="lightblue">
<script type = "text/javascript">
8 var childbook = new book("A Child's Garden of Verses",
"Robert Lewis Stevenson",
"Little Brown");
9 var adultbook = new book("War and Peace",
"Leo Tolstoy",
"Penguin Books");
10 childbook.show(); // Call method for child's book
11 adultbook.show(); // Call method for adult's book
</script>
</body>
</html>
Trang 7E X P L A N A T I O N
1 The book constructor function is defined with its properties.
2 The book object is described with three properties: title, author, and publisher.
3 The book object’s property is assigned the name of a function This property will
serve as a method for the object
4 A function called show is defined.
5 The with keyword will allow you to reference the properties of the object without
using the name of the object and the dot or the this keyword (See “The Math
Ob-ject” on page 241 in Chapter 9.)
6 A variable called info is assigned the property values of a book object The with
keyword allows you to specify the property name without a reference to the object
(and dot) preceding it
7 The alert box displays the properties for a book object.
8 The constructor function is called and returns an instance of a new book object
called childbook.
9 The constructor function is called and returns an instance of another book object
called adultbook.
10 The show() method is called for the childbook object (see Figure 8.10)
11 The show() method is called for the adultbook object (see Figure 8.11).
Figure 8.10 The childbook object and its properties.
Trang 8JavaScript provides the for/in loop, which can be used to iterate through a list of object
properties or array elements The for/in loop reads: for each property in an object (or for
each element in an array) get the name of each property (element), in turn, and for each
of the properties (elements), execute the statements in the block that follows
The for/in loop is a convenient mechanism for looping through the properties of an
object
Figure 8.11 The adultbook object and its properties.
F O RM A T
for(var property_name in object){
statements;
}
E X A M P L E 8 1 0
<html>
<head><title>User-defined objects</title>
<script type = "text/javascript">
1 function book(title, author, publisher){
this.author = author;
this.publisher = publisher;
3 this.show=show; // Define a method for the object
}
Trang 94 function show(obj, name){
// Function to show the object's properties
var result = "";
5 for (var prop in obj){
6 result += name + "." + prop + " = " +
obj[prop] + "<br />";
}
}
</script>
</head>
<body bgcolor="lightblue">
<script type="text/javascript">
8 myBook = new book("JavaScript by Example", "Ellie",
"Prentice Hall");
9 document.write("<br /><b>" + myBook.show(myBook, "myBook"));
</script>
</body>
</html>
E X P L A N A T I O N
1 The function called book will define the properties and methods for a book object.
The function is a template for the new object An instance of a new book object
will be created when this constructor is called
2 This is the first property defined for the book object The this keyword refers to
the current object
3 A show property of the object is assigned a function name also called show, thus
creating a method for the object
4 The function called show() is defined, tasked to display all the properties of the
object
5 The special for/in loop executes a set of statements for each property of the object.
6 The name and value of each property is concatenated and assigned to a variable
called result The value obj[prop] is used to key into each of the property values of
the book object.
7 The value of the variable result is sent back to the caller Each time through the
loop, another property and value are displayed
8 A new book object called myBook is created (instantiated).
9 The properties for the book object are shown in the browser window; see Figure
8.12 Notice how the method and its definition are displayed
E X A M P L E 8 1 0 (C O N T I N U E D)
Trang 108.5 Extending Objects with Prototypes
In object-oriented languages, like Java and C++, the object, along with its properties
(state) and methods (behavior), is bundled up into a container called a class These
pro-gramming languages all allow classes to reuse and extend an existing class; that is,
inherit commonly used state and behaviors from other classes A new class, called a
sub-class, can be derived from an existing class For example, if you have a Pet sub-class, let’s say
all pets have an owner, a gender, and some methods for setting and getting the
proper-ties We could create subclasses of the Pet, such as a Dog and Cat, because both the Dog
and Cat share the same properties as a Pet The code for the Pet can be extended to the
Dog and the Cat by using inheritance Then each subclass can be refined further by
add-ing its own specific features
Let’s look at an example of how JavaScript might use inheritance A constructor
func-tion called divStyle() has been defined It will be used to create div containers to style a
Web page The constructor defines the properties for a div, for example, the borders,
pad-ding, background color, and so on, and has a divGet() method to display the div in the
document Later we want to make divStyle objects but change or add properties; perhaps
change the width of the border or set a border color We can reuse or extend the divStyle
code by using inheritance
Section 8.2 explained that unlike Java and C++, JavaScript doesn’t have a class
mech-anism per se, but inheritance involves reusing or extending a class With JavaScript we
can simulate a class with a constructor function and the new keyword And to
imple-ment inheritance JavaScript extends a the class with a prototype (For those of you who
are Java or C++ programmers, JavaScript does not use keywords like extended, protected,
private, public, etc.) How does prototype inheritance work?
JavaScript functions are automatically given an empty prototype object If the function
acts as a constructor function for a class of objects, the prototype object can be used to
extend the class Each object created for the class is also given two properties, a constructor
property and a prototype property The constructor property is a reference to the function that
created this object, and the prototype property a reference to its prototype object This
prop-Figure 8.12 The book object’s properties.