Tải bản đầy đủ (.pdf) (674 trang)

1820 professional javascript for web developers

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (9.71 MB, 674 trang )

www.it-ebooks.info


www.it-ebooks.info


Professional JavaScript™ for Web Developers

www.it-ebooks.info


www.it-ebooks.info


Professional JavaScript™ for Web Developers
Nicholas C. Zakas

www.it-ebooks.info


Professional JavaScript™ for Web Developers
Copyright © 2005 by Wiley Publishing Inc. All rights reserved.
Published by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form
or by any means, electronic, mechanical, photocopying, recording, scanning, or otherwise, except as
permitted under Section 107 or 108 of the 1976 United States Copyright Act, without either the prior
written permission of the Publisher, or authorization through payment of the appropriate per-copy fee
to the Copyright Clearance Center, Inc., 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax
(978) 646-8700. Requests to the Publisher for permission should be addressed to the Legal Department,
Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317)


572-4355, or online at www.wiley.com/go/permissions.
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR
MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR
COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL
WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE
SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT
THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A
COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOT
THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN
ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A
POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR
THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY
PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE
THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED
BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.
For general information on our other products and services please contact our Customer Care Department within the United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317)
572-4002.
Trademarks: Wiley, the Wiley Publishing logo, Wrox, the Wrox logo, and Programmer to Programmer
are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates. JavaScript is a
trademark of Sun Microsystems, Inc. in the United States and other countries. All other trademarks are
the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or
vendor mentioned in this book.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print
may not be available in electronic books.
Library of Congress Cataloging-in-Publication Data is available from the publisher.
ISBN-13: 978-0-7645-7908-0
ISBN-10: 0-7645-7908-8
Printed in the United States of America
10 9 8 7 6 5 4 3 2 1


www.it-ebooks.info


About the Author
Nicholas C. Zakas is a user interface designer for Web applications, specializing in client-side technologies such as JavaScript, HTML, and CSS. Nicholas currently works as Senior Software Engineer, Design
Engineering, at MatrixOne, Inc. located in Westford, Massachusetts, USA.
Nicholas has a B.S. in Computer Science from Merrimack College, where he learned traditional programming in C and C++. During college, he began investigating the World Wide Web and HTML in his
spare time, eventually teaching himself enough to be hired as Webmaster of a small software company
named Radnet, Inc. in Wakefield, Massachusetts, USA. It was there that Nicholas began learning
JavaScript and working on Web applications.
Nicholas can be reached through his Web site, />
www.it-ebooks.info


Credits
Vice President and Executive Group Publisher:

Development Editor:

Richard Swadley

Sharon Nash

Vice President and Publisher:

Senior Production Editor:

Joseph B. Wikert

Angela Smith


Acquisitions Editor:

Technical Editor:

Jim Minatel

Jean-Luc David, Wiley-Dreamtech India Pvt Ltd

Editorial Manager:

Text Design & Composition:

Mary Beth Wakefield

Wiley Composition Services

www.it-ebooks.info


Acknowledgments
It takes more than just one person to write a book of this nature, despite the single name on the front
cover. Without the help of numerous individuals, this book would not have been possible.
First are foremost, thanks to everyone at Wiley Publishing, especially Jim Minatel and Sharon Nash, for
providing all the guidance and support that a new author needs.
Thanks to all those who offered their ideas on what a good JavaScript book should include: Keith
Ciociola, Ken Fearnley, John Rajan, and Douglas Swatski.
A special thanks to everyone who reviewed the subject matter ahead of time: Erik Arvidsson, Bradley
Baumann, Guilherme Blanco, Douglas Crockford, Jean-Luc David, Emil A. Eklund, Brett Fielder, Jeremy
McPeak, and Micha Schopman. All your input was excellent and made for a much better book.

Thanks to Drs. Ed and Frances Bernard for keeping me in tip-top health during the writing of this book
and the past few years.
Last, but certainly not least, thanks to my family, mom, dad, and Greg, and my extremely understanding
girlfriend, Emily. Your love and support helped take me from the proposal to the final published copy.

vii
www.it-ebooks.info


www.it-ebooks.info


Contents
Acknowledgments
Introduction

vii
xxi

Chapter 1: What Is JavaScript?
A Short History
JavaScript Implementations

1
1
3

ECMAScript
The Document Object Model (DOM)
The Browser Object Model (BOM)


Summary

3
6
9

9

Chapter 2: ECMAScript Basics

11

Syntax
Variables
Keywords
Reserved Words
Primitive and Reference Values
Primitive Types

11
12
15
15
15
16

The
The
The

The
The
The

typeof operator
Undefined type
Null type
Boolean type
Number type
String type

16
17
18
18
18
20

Conversions

21

Converting to a string
Converting to a number
Type Casting

22
23
24


Reference Types

25

The Object class
The Boolean class
The Number class

26
27
27

ix
www.it-ebooks.info


Contents
The String class
The instanceof operator

29
32

Operators

33

Unary operators
Bitwise operators
Boolean operators

Multiplicative operators
Additive operators
Relational operators
Equality operators
Conditional operator
Assignment operators
Comma operator

33
37
43
46
47
49
50
52
52
53

Statements

53

The if statement
Iterative statements
Labeled statements
The break and continue statements
The with statement
The switch statement


53
54
56
56
58
58

Functions

59

No overloading
The arguments object
The Function class
Closures

61
62
63
65

Summary

66

Chapter 3: Object Basics

67

Object-Oriented Terminology


67

Requirements of object-oriented languages
Composition of an object

Working with Objects

68
68

68

Declaration and instantiation
Object references
Dereferencing objects
Early versus late binding

68
69
69
69

Types of Objects

70

Native objects
Built-in objects
Host objects


70
81
87

x
www.it-ebooks.info


Contents
Scope

88

Public, protected, and private
Static is not static
The this keyword

Defining Classes and Objects
Factory paradigm
Constructor paradigm
Prototype paradigm
Hybrid constructor/prototype paradigm
Dynamic prototype method
Hybrid factory paradigm
Which one to use?
A practical example

Modifying Objects


88
88
89

90
90
92
93
94
95
96
97
97

99

Creating a new method
Redefining an existing method
Very late binding

Summary

99
100
101

102

Chapter 4: Inheritance


103

Inheritance in Action
Implementing Inheritance

103
104

Methods of inheritance
A more practical example

105
111

Alternative Inheritance Paradigms
zInherit
xbObjects

115
116
120

Summary

124

Chapter 5: JavaScript in the Browser
JavaScript in HTML

125

125

The <script/> tag
External file format
Inline code versus external files
Tag placement
To hide or not to hide
The <noscript/> tag
Changes in XHTML

125
126
127
128
129
130
131

xi
www.it-ebooks.info


Contents
JavaScript in SVG

133

Basic SVG
The <script/> tag in SVG
Tag placement in SVG


133
134
135

The Browser Object Model

136

The
The
The
The
The

window object
document object
location object
navigator object
screen object

136
149
153
155
156

Summary

157


Chapter 6: DOM Basics

159

What Is the DOM?

159

Introduction to XML
An API for XML
Hierarchy of nodes
Language-Specific DOMs

159
162
163
166

DOM Support
Using the DOM

167
167

Accessing relative nodes
Checking the node type
Dealing with attributes
Accessing specific nodes
Creating and manipulating nodes


167
169
169
171
173

DOM HTML Features

178

Attributes as properties
Table methods

178
179

DOM Traversal

182

NodeIterator
TreeWalker

182
187

Detecting DOM Conformance
DOM Level 3
Summary


189
191
191

Chapter 7: Regular Expressions

193

Regular Expression Support

193

Using a RegExp object
Extended string methods

194
195

xii
www.it-ebooks.info


Contents
Simple Patterns

197

Metacharacters
Using special characters

Character classes
Quantifiers

197
197
199
201

Complex Patterns

205

Grouping
Backreferences
Alternation
Non-capturing groups
Lookaheads
Boundaries
Multiline mode

205
206
207
209
210
210
212

Understanding the RegExp Object
Instance properties

Static properties

212
213
214

Common Patterns

216

Validating dates
Validating credit cards
Validating e-mail addresses

216
218
222

Summary

223

Chapter 8: Browser and Operating System Detection
The Navigator Object
Methods of Browser Detection
Object/feature detection
User-agent string detection

225
225

226
226
226

A (Not So) Brief History of the User-Agent String
Netscape Navigator 3.0 and Internet Explorer 3.0
Netscape Communicator 4.0 and Internet Explorer 4.0
Internet Explorer 5.0 and higher
Mozilla
Opera
Safari
Epilogue

The Browser Detection Script
Methodology
First Steps
Detecting Opera

227
227
229
230
230
232
233
233

234
234
234

237

xiii
www.it-ebooks.info


Contents
Detecting
Detecting
Detecting
Detecting

Konqueror/Safari
Internet Explorer
Mozilla
Netscape Communicator 4.x

239
241
242
243

The Platform/Operating System Detection Script

244

Methodology
First steps
Detecting Windows operating systems
Detecting Macintosh operating systems

Detecting Unix operating systems

The Full Script
Example: A Login Page
Summary

244
245
245
247
248

249
252
259

Chapter 9: All about Events

261

Events Today
Event Flow

261
262

Event bubbling
Event capturing
DOM event flow


262
264
265

Event Handlers/Listeners

266

Internet Explorer
DOM

267
268

The Event Object

270

Locating
Properties/methods
Similarities
Differences

270
271
274
276

Types of Events


279

Mouse events
Keyboard events
HTML events
Mutation events

280
284
286
291

Cross-Browser Events

292

The EventUtil object
Adding/removing event handlers
Formatting the event object
Getting the event object
Example

292
292
294
299
300

Summary


301

xiv
www.it-ebooks.info


Contents
Chapter 10: Advanced DOM Techniques
Scripting Styles

303
303

DOM style methods
Custom tooltips
Collapsible sections
Accessing style sheets
Computed styles

305
307
308
309
312

innerText and innerHTML
outerText and outerHTML
Ranges

314

315
317

Ranges in the DOM
Ranges in Internet Explorer
How practical are ranges?

317
329
333

Summary

333

Chapter 11: Forms and Data Integrity
Form Basics
Scripting the <form/> Element
Getting form references
Accessing form fields
Form field commonalities
Focus on the first field
Submitting forms
Submit only once
Resetting forms

335
335
337
337

338
338
339
340
341
342

Text boxes

342

Retrieving/changing a text box value
Selecting text
Text box events
Select text automatically
Tab forward automatically
Limit textarea characters
Allowing/blocking characters in text boxes
Numeric text boxes with the up/down arrow keys

List Boxes and Combo Boxes
Accessing options
Retrieving/changing the selected option(s)
Adding options
Removing options

343
344
345
345

346
347
349
354

356
357
357
359
360

xv
www.it-ebooks.info


Contents
Moving Options
Reordering options

361
361

Creating an Autosuggest Text Box

362

Matching
The guts

362

363

Summary

365

Chapter 12: Sorting Tables

367

The Starting Point — Arrays

367

The reverse() method

369

Sorting a One-Column Table

369

The comparison function
The sortTable() function

371
371

Sorting a Multicolumn Table


373

The comparison function generator
Modifying the sortTable() function
Sorting in descending order
Sorting with different data types
Advanced sorting

374
375
376
377
381

Summary

385

Chapter 13: Drag and Drop

387

System Drag and Drop

387

Drag-and-drop events
The dataTransfer object
The dragDrop() method
Advantages and disadvantages


388
393
397
399

Simulated Drag and Drop

399

The code
Creating drop targets
Advantages and disadvantages

400
403
405

zDragDrop

405

Creating a draggable element
Creating a drop target
Events
Example

406
406
406

408

Summary

409

xvi
www.it-ebooks.info


Contents
Chapter 14: Error Handling

411

The Importance of Error Handling
Errors versus Exceptions
Error Reporting
Internet Explorer (Windows)
Internet Explorer (MacOS)
Mozilla (all platforms)
Safari (MacOS X)
Opera 7 (all platforms)

411
412
413
413
415
416

417
418

Handling Errors

419

The onerror event handler
The try...catch statement

419
423

Debugging Techniques

428

Using alerts
Using the Java console
Posting messages to the JavaScript console (Opera 7+ only)
Throwing your own errors
The JavaScript Verifier

Debuggers

428
429
430
431
432


432

Microsoft Script Debugger
Venkman – Mozilla’s debugger

Summary

432
435

443

Chapter 15: XML in JavaScript

445

XML DOM Support in Browsers

445

XML DOM support in IE
XML DOM support in Mozilla
Making interfaces play together

445
450
455

XPath Support in Browsers


465

Introduction to XPath
XPath support in IE
XPath support in Mozilla

466
467
467

XSLT Support in Browsers

471

XSLT support in IE
XSLT support in Mozilla

473
477

Summary

479

xvii
www.it-ebooks.info


Contents

Chapter 16: Client-Server Communication
Cookies

481
481

Cookie ingredients
Other security restrictions
Cookies in JavaScript
Cookies on the server
Passing cookies between client and server

Hidden Frames

482
482
483
485
488

490

Using iframes

491

HTTP Requests

493


Using headers
Copycat implementations
Performing a GET request
Performing a POST request

495
496
496
497

LiveConnect Requests

498

Performing a GET request
Performing a POST request

498
500

Intelligent HTTP Requests

502

The get() method
The post() method

502
505


Practical Uses
Summary

506
507

Chapter 17: Web Services

509

A Quick Web Service Primer

509

What is a Web service?
WSDL

509
510

Web Services in Internet Explorer

513

Using the WebService component
WebService component example

513
515


Web Services in Mozilla

516

Enhanced privileges
Using the SOAP methods
Using WSDL proxies

517
518
522

A Cross-Browser Approach

525

The WebService object
The Temperature Service
Using the TemperatureService object

525
527
529

Summary

530

xviii
www.it-ebooks.info



Contents
Chapter 18: Interacting with Plugins
Why Use Plugins?
Popular Plugins
MIME Types
Embedding Plugins

531
531
532
533
533

Including parameters
Netscape 4.x

534
534

Detecting Plugins

535

Detecting Netscape-style plugins
Detecting ActiveX plugins
Cross-browser detection

Java Applets


535
540
542

543

Embedding applets
Referencing applets in JavaScript
Writing applets
JavaScript-to-Java communication
Java-to-JavaScript communication

Flash Movies

543
544
545
546
548

551

Embedding Flash movies
Referencing Flash movies
JavaScript-to-Flash communication
Flash-to-JavaScript communication

ActiveX Controls
Summary


552
552
553
555

558
561

Chapter 19: Deployment Issues
Security

563
563

The Same Origin Policy
Window object issues
Mozilla-specific issues
Resource limitations

563
564
566
568

Internationalization Concerns
Detecting language using JavaScript
Strategies
String considerations


Optimizing JavaScript

568
569
569
570

573

Download time
Execution time

573
578

xix
www.it-ebooks.info


Contents
Intellectual Property Issues

593

Obfuscating
Microsoft Script Encoder (IE only)

593
594


Summary

595

Chapter 20: The Evolution of JavaScript
ECMAScript 4

597
597

Netscape’s proposal
Implementations

598
604

ECMAScript for XML

605

Approach
The for each..in Loop
New classes
Implementations

605
607
607
616


Summary

616

Index

617

xx
www.it-ebooks.info


Introduction
Although once supported by Netscape Enterprise Server and Active Server Pages (ASP) on the server,
JavaScript is primarily a client-side scripting language for use in Web browsers. Its main focus today is
to help developers interact with Web pages and the Web browser window itself.
JavaScript is very loosely based on Java, an object-oriented programming language popularized for use
on the Web by way of embedded applets. Although JavaScript has a similar syntax and programming
methodology, it is not a “light” version of Java. Instead, JavaScript is its own language, finding its home
in Web browsers around the world and enabling enhanced user interaction on Web sites and Web applications alike.
In this book, JavaScript is covered from its very beginning in the earliest Netscape browsers to the
present-day incarnations flush with support for XML and Web Services. You learn how to extend the
language to suit specific needs and how to create seamless client-server communication without intermediaries such as Java or hidden frames. In short, you learn how to apply JavaScript solutions to
business problems faced by Web developers everywhere.

What Does This Book Cover?
Professional JavaScript for Web Developers provides a developer-level introduction along with the more
advanced and useful features of JavaScript.
Starting at the beginning, the book explores how JavaScript originated and evolved into what it is today.
A detailed discussion of the components that make up a JavaScript implementation follows, with specific focus on standards such as ECMAScript and the Document Object Model (DOM). The differences in

JavaScript implementations used in different popular Web browsers are also discussed.
Building on that base, the book moves on to cover basic concepts of JavaScript including its version of
object-oriented programming, inheritance, and its use in various markup languages such as HTML. An
in-depth examination of events and event handling is followed by an exploration of browser detection
techniques and a guide to using regular expressions in JavaScript. The book then takes all this knowledge and applies it to creating dynamic user interfaces.
The last part of the book is focused on issues related to the deployment of JavaScript solutions in Web
applications. These topics include error handling, debugging, security, optimization/obfuscation, XML,
and Web Services.

xxi
www.it-ebooks.info


Introduction

Who Is This Book For?
This book is aimed at three groups of readers:


Experienced developers familiar with object-oriented programming who are looking to learn
JavaScript as it relates to traditional OO languages such as Java and C++.



Web application developers attempting to enhance the usability of their Web sites and Web
applications.



Novice JavaScript developers aiming to better understand the language.


In addition, familiarity with the following related technologies is a strong indicator that this book is
for you:


XML



XSLT



Java



Web Services



HTML



CSS

This book is not aimed at beginners lacking a basic computer science background or those looking to
add some simple user interactions to Web sites. These readers should instead refer to Wrox’s Beginning
JavaScript, Second Edition (Wiley Publishing, Inc., ISBN 0-7645-5587-1).


What You Need to Use This Book
To run the samples in the book, you need the following:


Windows 2000, Windows Server 2003, Windows XP, or Mac OS X



Internet Explorer 5.5 or higher (Windows), Mozilla 1.0 or higher (all platforms), Opera 7.5 or
higher (all platforms), or Safari 1.2 or higher (Mac OS X).

The complete source code for the samples is available for download from the Web site at
/>
How Is This Book Structured?
1.

What Is JavaScript?
This chapter explains the origins of JavaScript: where it came from, how it evolved, and what it
is today. Concepts introduced include the relationship between JavaScript and ECMAScript, the
Document Object Model (DOM), and the Browser Object Model (BOM). A discussion of the relevant standards from the European Computer Manufacturer’s Association (ECMA) and the
World Wide Web Consortium (W3C) is also included.

xxii
www.it-ebooks.info


Introduction
2.


ECMAScript Basics
This chapter examines the core technology upon which JavaScript is built, ECMAScript. This
chapter describes the basic syntax and concepts necessary to write JavaScript code, from declaring variables and functions to using and understanding primitive and reference values.

3.

Object Basics
This chapter focuses on the foundations of object-oriented programming (OOP) in JavaScript.
Topics covered include defining custom objects using a variety of different methods, creating
object instances, and understanding the similarities and differences to OOP in JavaScript and Java.

4.

Inheritance
This chapter continues the exploration of OOP in JavaScript, describing how inheritance works.
The various methods of achieving inheritance are discussed, and these methods are compared
and contrasted with inheritance in Java.

5.

JavaScript in the Browser
This chapter explains how to include JavaScript in Web pages made with a variety of languages,
including Hyper Text Markup Language (HTML), Scalable Vector Graphics (SVG), and XML
User Interface Language (XUL). This chapter also introduces the Browser Object Model (BOM)
and its various objects and interfaces.

6.

DOM Basics
This chapter introduces the DOM as implemented in JavaScript. It includes an introduction to

DOM concepts of specific value to Web developers. These concepts are applied later in examples using HTML, SVG, and XUL.

7.

Regular Expressions
This chapter focuses on the JavaScript implementation of regular expressions, which are a powerful tool for data validation and string manipulation. The origins of regular expressions are
explored, as well as its syntax and usage across a variety of programming languages. The chapter ends with an explanation of the similarities and differences in JavaScript’s implementation.

8.

Browser and Operating System Detection
This chapter explains the importance of writing JavaScript to run on a variety of Web browsers.
The two methods of browser detection, object/feature detection and user-agent string detection,
are discussed; the advantages and disadvantages of each approach are listed.

9.

All about Events
This chapter discusses one of the most important concepts in JavaScript: events. Events are the
main way to tie JavaScript to a Web-user interface regardless of the markup language being
used. This chapter describes the various methods of handling events and the concept of event
flow (including bubbling and capturing).

10.

Advanced DOM Techniques
This chapter introduces some of the more advanced features of the DOM, including ranges and
style-sheet manipulation. I give examples of when and how to use these technologies, and I also
discuss how to achieve cross-browser support given the differences in implementations.


xxiii
www.it-ebooks.info


×