Вы находитесь на странице: 1из 1080

cover_JavaScript_6ed:Layout 3

01.06.2012

20:36

Page 1

TML
H
ript 5
Sc
MA
6 EC

JavaScript.

JavaScript,

XML$
<canvas>
SVG
, ,
, HTML5
jQuery

I JavaScript. II , . JavaScript DOM. JavaScript , , :

HTML$
-


HTML$
$
Ajax
XPath XSLT XML$, Ajax

, WebSockets

WebWorkers

III JavaScript , , , , , , JavaScript 1.8, V8 3.0


ECMAScript 5. IV JavaScript, API
$, DOM API Level 3 HTML5
WebSockets WebWorkers, localStorage sessionStorage, <audio> <video>.


(812) 3805007, (495) 6385305

www.symbol.ru

JavaScript

: -/JavaScript

JavaScript

HTTP Ajax

ECMAScript 5 HTML5

, JavaScript
Web 2.0.
JavaScript
, .
, JavaScript:

JavaScript
The Definitive Guide
Sixth Edition

David Flanagan

JavaScript


2012

JavaScript. ,
6
.

.

.
.
.
.
.

.
JavaScript. , 6 . . . : 
, 2012. 1080 ., .
ISBN 9785932862155
JavaScript.
JavaScript 
Web 2.0. 

, JavaScript 
, .
ECMAScript 5 HTML5. 
, ,
jQuery JavaScript .
I JavaScript. II 
, . 
JavaScript
DOM. III JavaScript,
, , , , 
, , JavaScript 1.8, V8 3.0 ECMAScript 5.
IV JavaScript. API 
, DOM API Level 3 HTML5
WebSockets WebWorkers, localStorage sessionStorage,
<audio> <video>.
,
, ,
JavaScript .
ISBN 9785932862155
ISBN 9780596805524 ()
, 2012
Authorized Russian translation of the English edition of JavaScript: The Definitive
Guide, Sixth Edition ISBN 9780596805524 2011 OReilly Media, Inc. This transla
tion is published and sold by permission of OReilly Media, Inc., the owner of all rights
to publish and sell the same.
, 
. 
, , .

. 199034, , 16 , 7,
. (812) 3805007, www.symbol.ru. N 000054 25.12.98.
30.05.2012. 701001/16 .
. 67,5 . .

,
.

 17

1. JavaScript 21

1.1. JavaScript  25
1.2. JavaScript 29
1.2.1. : JavaScript  33

I. JavaScript 39
2.  41
2.1.  41
2.1.1.  41
2.1.2. ,  42
2.1.3.  42
2.1.4.  43
2.2.  43
2.3.  43
2.4.  44
2.4.1.  44
2.5.  46

3. ,  49
3.1.  51
3.1.1.  52
3.1.2.  52
3.1.3. JavaScript  53
3.1.4.
 55
3.1.5.  56
3.2.  56
3.2.1.  56
3.2.2.  58
3.2.3.  59
3.2.4.  60
3.3.  61
3.4. null undefined 62
3.5.  63
3.6. - 64
3.7.  65

3.8.  67
3.8.1.  68
3.8.2.  69
3.8.3.  71
3.9.  74
3.9.1  74
3.10.  75
3.10.1.  76
3.10.2.  77
3.10.3  78

4.  79
4.1.  79
4.2.  80
4.3.  81
4.4.  82
4.5.  83
4.6.  84
4.7.  84
4.7.1.  86
4.7.2.  86
4.7.3.  86
4.7.4.  87
4.7.5.  87
4.7.6.  88
4.7.7.  88
4.8.  88
4.8.1. + 89
4.8.2.  90
4.8.3.  91
4.9.  93
4.9.1.  93
4.9.2.  95
4.9.3. in  97
4.9.4. instanceof 97
4.10.  98
4.10.1. (&&) 98
4.10.2. (||) 99
4.10.3. (!) 100
4.11.  100
4.11.1.  101
4.12.  102
4.12.1. eval() 103
4.12.2. eval()  103
4.12.3. eval()  104
4.13.  105
4.13.1. (?:) 105
4.13.2. typeof 105
4.13.3. delete  107
4.13.4. void 108
4.13.5. (,) 108

5.  109
5.1. - 110
5.2.  110
5.3. -  112
5.3.1. var 112
5.3.2. function  113
5.4.  114
5.4.1. if  114
5.4.2. else if 116
5.4.3. switch  117
5.5.  119
5.5.1. while  119
5.5.2. do/while  120
5.5.3. for 121
5.5.4. for/in 122
5.6.  124
5.6.1.  124
5.6.2. break 125
5.6.3. continue  126
5.6.4. return  127
5.6.5. throw 128
5.6.6. try/catch/finally 129
5.7.  131
5.7.1. with  131
5.7.2. debugger  132
5.7.3. "use strict"  133
5.8. JavaScript- 135

6.  137
6.1.  139
6.1.1.  139
6.1.2. new 140
6.1.3.  140
6.1.4. Object.create() 141
6.2.  142
6.2.1.  143
6.2.2.  144
6.2.3.  145
6.3.  147
6.4.  148
6.5.  149
6.6.  152
6.7.  154
6.7.1.  157
6.8.  158
6.8.1. prototype 158
6.8.2. class 159
6.8.3. extensible 160
6.9.  161
6.10. Object  162
6.10.1. toString() 162
6.10.2. toLocaleString()  163

6.10.3. toJSON()  163


6.10.4. valueOf()  163

7.  164
7.1.  165
7.2.  166
7.3.  167
7.4.  168
7.5.  169
7.6.  170
7.7.  171
7.8. Array 172
7.8.1. join()  172
7.8.2. reverse() 172
7.8.3. sort()  173
7.8.4. concat()  173
7.8.5. slice()174
7.8.6. splice()174
7.8.7. push() pop()  175
7.8.8. unshift() shift() 175
7.8.9. toString() toLocaleString()  176
7.9. Array,
ECMAScript5 176
7.9.1. forEach()  176
7.9.2. map()  177
7.9.3. filter()  177
7.9.4. every() some() 178
7.9.5. reduce() reduceRight() 178
7.9.6. indexOf() lastIndexOf()  180
7.10. Array 181
7.11. ,  182
7.12.  184

8.  185
8.1.  185
8.1.1.  188
8.2.  189
8.2.1.  189
8.2.2.  190
8.2.3.  192
8.2.4.  193
8.3.  193
8.3.1.  193
8.3.2. : Arguments 194
8.3.3.  196
8.3.4.  197
8.4.  198
8.4.1.  200
8.5.  201
8.6.  203
8.7. Function 209
8.7.1. length  209

10

8.7.2. prototype 209


8.7.3. call() apply() 210
8.7.4. bind()  211
8.7.5. toString() 213
8.7.6. Function() 213
8.7.7.  214
8.8.  215
8.8.1.  215
8.8.2.  217
8.8.3.  218
8.8.4.  220

9.  221
9.1.  222
9.2.  223
9.2.1.  225
9.2.2. constructor 226
9.3. Java 227
9.4.  231
9.5.  232
9.5.1. instanceof 232
9.5.2. constructor 233
9.5.3.  234
9.5.4.  235
9.6. - JavaScript 238
9.6.1. :  238
9.6.2. : -  239
9.6.3.  242
9.6.4.  244
9.6.5.  247
9.6.6.  249
9.6.7.  250
9.7.  252
9.7.1.  252
9.7.2.  254
9.7.3.  256
9.7.4.  258
9.8. ECMAScript5 262
9.8.1.  262
9.8.2.  263
9.8.3.  265
9.8.4.  266
9.8.5. ECMAScript5  267
9.8.6.  268
9.9.  270
9.9.1.  271
9.9.2.  273

10.  276
10.1.  276
10.1.1.  277
10.1.2.  278

11

10.1.3.  279
10.1.4. ,  281
10.1.5.  283
10.1.6.  284
10.2. String  285
10.3. RegExp 287
10.3.1. RegExp  288
10.3.2. RegExp 288

11. JavaScript 290


11.1. JavaScript  291
11.1.1. The Good Parts  291
11.1.2.  292
11.2.  295
11.3.  298
11.4.  300
11.4.1. for/each 300
11.4.2.  301
11.4.3.  303
11.4.4.  307
11.4.5. -  308
11.5.  309
11.6. catch 309
11.7. E4X: ECMAScript for XML  310

12. JavaScript 314


12.1. Java Rhino 315
12.1.1. Rhino 319
12.2. / Node  321
12.2.1. Node: HTTP- 327
12.2.2. Node: HTTP  329

II. JavaScript  331


13. JavaScript - 333
13.1. JavaScript  333
13.1.1. JavaScript - 336
13.1.2. JavaScript - 336
13.2. JavaScript- HTML 337
13.2.1. <script> 338
13.2.2.  339
13.2.3.  340
13.2.4. HTML 341
13.2.5. JavaScript URL 342
13.3. JavaScript-  344
13.3.1. ,  345
13.3.2. ,  347
13.3.3. JavaScript 349
13.3.4.  350
13.4.  352
13.4.1.  356

12

13.4.2.  356
13.4.3.  357
13.4.4.  358
13.4.5.  358
13.4.6. Internet Explorer 359
13.5.  360
13.6.  361
13.6.1. JavaScript  362
13.6.2.  363
13.6.3.
ActiveX  365
13.6.4.  365
13.6.5.  367
13.7.  367

14. Window 369


14.1.  370
14.2.  371
14.2.1. URL 371
14.2.2.  372
14.3.  373
14.4.  374
14.4.1. Navigator 374
14.4.2. Screen  377
14.5.  377
14.6.  379
14.7.  380
14.8.  382
14.8.1.  383
14.8.2.  385
14.8.3. JavaScript  387

15.  390
15.1. DOM 390
15.2.  393
15.2.1. id 393
15.2.2. name 394
15.2.3.  395
15.2.4. CSS  397
15.2.5. CSS 398
15.2.6. document.all[] 400
15.3.  401
15.3.1.  401
15.3.2.  402
15.4.  405
15.4.1. HTML- Element 405
15.4.2. HTML-  406
15.4.3.  407
15.4.4. Attr 408
15.5.  409
15.5.1. HTML 409
15.5.2.  410

13

15.5.3.  411
15.6. ,  412
15.6.1.  413
15.6.2.  413
15.6.3.  415
15.6.4. DocumentFragment  416
15.7. :  418
15.8.  421
15.8.1.  421
15.8.2.  423
15.8.3.  424
15.8.4.  425
15.8.5. ,  426
15.9. HTML- 428
15.9.1.  430
15.9.2.  431
15.9.3.  432
15.9.4.  433
15.9.5.  434
15.9.6.  434
15.9.7. Select Option 435
15.10.  437
15.10.1. Document  437
15.10.2. document.write()  438
15.10.3.  440
15.10.4.  441

16.  444
16.1. CSS 445
16.1.1.  446
16.1.2. CSS 447
16.1.3.  447
16.1.4.  447
16.1.5. CSS-  448
16.2. CSS- 450
16.2.1. CSS  451
16.2.2. ,  454
16.2.3. CSS 455
16.2.4.  457
16.2.5. ,  458
16.2.6. : overflow clip 459
16.2.7. :  460
16.3.  463
16.3.1.
CSS  465
16.4.  468
16.5. CSS- 470
16.6.  472
16.6.1.  472
16.6.2. ,  473
16.6.3.  474

14

17.  476
17.1.  479
17.1.1.  479
17.1.2. DOM  485
17.1.3. HTML5 486
17.1.4. ,
 488
17.2.  489
17.2.1.  489
17.2.2.  490
17.2.3. addEventListener() 491
17.2.4. attachEvent()  492
17.3.  492
17.3.1.  493
17.3.2.  493
17.3.3.  494
17.3.4.  495
17.3.5.  495
17.3.6.  496
17.3.7.  497
17.4.  498
17.5.  500
17.6.  504
17.7. (drag-and-drop) 508
17.8.  515
17.9.  518

18. HTTP 524


18.1. XMLHttpRequest 527
18.1.1.  529
18.1.2.  531
18.1.3.  535
18.1.4. , HTTP-  541
18.1.5.  544
18.1.6. HTTP-  545
18.2. HTTP- <script>: JSONP 548
18.3. Comet Server-Sent Events  550

19. jQuery  556


19.1. jQuery  557
19.1.1. jQuery()  558
19.1.2.  562
19.2. jQuery  565
19.2.1. HTML-  565
19.2.2. CSS-  566
19.2.3. CSS-  566
19.2.4. HTML-  567
19.2.5.  568
19.2.6.  568
19.2.7.  570
19.3.  571

15

19.3.1.  571
19.3.2.  573
19.3.3.  574
19.3.4.  574
19.4. jQuery 575
19.4.1.  575
19.4.2. jQuery 577
19.4.3. Event jQuery  577
19.4.4.  579
19.4.5.  580
19.4.6.  582
19.4.7.  584
19.4.8.  584
19.5.  586
19.5.1.  588
19.5.2.  589
19.5.3. ,  593
19.6. Ajax jQuery  595
19.6.1. load()  595
19.6.2. Ajax 597
19.6.3. jQuery.ajax()  602
19.6.4. Ajax 608
19.7.  610
19.8. jQuery 613
19.8.1. jQuery  613
19.8.2.  618
19.9. jQuery  622
19.10. jQuery UI  625

20.  627
20.1. localStorage sessionStorage 630
20.1.1.  630
20.1.2. Storage 632
20.1.3. Storage  633
20.2. Cookies  634
20.2.1. cookie:  635
20.2.2. cookies  637
20.2.3. cookies 638
20.2.4. cookies 639
20.2.5. cookies 639
20.3. userData IE  641
20.4. -  643
20.4.1.  643
20.4.2.  645
20.4.3. - 650

21.  655
21.1.  656
21.1.1.  657
21.2. -  658
21.2.1.  659
21.2.2.  660

16

21.2.3.  661
21.2.4  663
21.3. SVG  665
21.4. <canvas>  672
21.4.1.  675
21.4.2.  678
21.4.3.  679
21.4.4.  680
21.4.5.  685
21.4.6.  687
21.4.7. , ,  687
21.4.8.  691
21.4.9.  692
21.4.10.  693
21.4.11.  695
21.4.12.  696
21.4.13.  698
21.4.14.  701
21.4.15.  703
21.4.16. <canvas>:
 704

22. HTML5 706


22.1.  707
22.2.  711
22.3.  716
22.4.  720
22.4.1. Worker 721
22.4.2.  722
22.4.3.  725
22.5.  728
22.6.  732
22.6.1.  734
22.6.2.  735
22.6.3.  736
22.6.4. URL-,  736
22.6.5.  739
22.7.  742
22.8.  747
22.9. - 755

III. JavaScript  759

JavaScript 761
arguments[]
Arguments
Arguments.callee
Arguments.length
Array
Array.concat()
Array.every()
Array.filter()
Array.forEach()
Array.indexOf()
Array.join()
Array.lastIndexOf()
Array.length
Array.map()
Array.pop()
Array.push()
Array.reduce()
Array.reduceRight()
Array.reverse()
Array.shift()
Array.slice()
Array.some()
Array.sort()
Array.splice()
Array.toLocaleString()
Array.toString()
Array.unshift()
Boolean
Boolean.toString()
Boolean.valueOf()
Date
Date.getDate()
Date.getDay()
Date.getFullYear()
Date.getHours()
Date.getMilliseconds()
Date.getMinutes()
Date.getMonth()
Date.getSeconds()
Date.getTime()
Date.getTimezoneOffset()
Date.getUTCDate()
Date.getUTCDay()
Date.getUTCFullYear()
Date.getUTCHours()
Date.getUTCMilliseconds()
Date.getUTCMinutes()
Date.getUTCMonth()
Date.getUTCSeconds()
Date.getYear()
Date.now()
Date.parse()
Date.setDate()
Date.setFullYear()
Date.setHours()
Date.setMilliseconds()
Date.setMinutes()
Date.setMonth()
Date.setSeconds()
Date.setTime()
Date.setUTCDate()
Date.setUTCFullYear()
Date.setUTCHours()
Date.setUTCMilliseconds()
Date.setUTCMinutes()
Date.setUTCMonth()
Date.setUTCSeconds()
Date.setYear()
Date.toDateString()
Date.toGMTString()
Date.toISOString()
Date.toJSON()
Date.toLocaleDateString()
Date.toLocaleString()
Date.toLocaleTimeString()
Date.toString()
Date.toTimeString()
Date.toUTCString()
Date.UTC()
Date.valueOf()
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
Error
Error.message
Error.name
Error.toString()
escape()
eval()
EvalError
Function
Function.apply()
Function.arguments[]
Function.bind()
Function.call()
Function.caller
Function.length
Function.prototype
Function.toString()
Global
Infinity
isFinite()
isNaN()
JSON
JSON.parse()
JSON.stringify()
Math
Math.abs()
Math.acos()
Math.asin()
Math.atan()
Math.atan2()
Math.ceil()
Math.cos()
Math.E
Math.exp()
Math.floor()
Math.LN10
Math.LN2
Math.log()
Math.LOG10E
Math.LOG2E
Math.max()
Math.min()
Math.PI
Math.pow()
Math.random()
Math.round()
Math.sin()
Math.sqrt()
Math.SQRT1_2
Math.SQRT2
Math.tan()
NaN
Number
Number.MAX_VALUE
Number.MIN_VALUE
Number.NaN
Number.NEGATIVE_INFINITY
Number.POSITIVE_INFINITY
Number.toExponential()
Number.toFixed()
Number.toLocaleString()
Number.toPrecision()
Number.toString()
Number.valueOf()
Object
Object.constructor
Object.create()
Object.defineProperties()
Object.defineProperty()
Object.freeze()
Object.getOwnPropertyDescriptor()
Object.getOwnPropertyNames()
Object.getPrototypeOf()
Object.hasOwnProperty()
Object.isExtensible()
Object.isFrozen()
Object.isPrototypeOf()
Object.isSealed()
Object.keys()
Object.preventExtensions()
Object.propertyIsEnumerable()
Object.seal()
Object.toLocaleString()
Object.toString()
Object.valueOf()
parseFloat()
parseInt()
RangeError
ReferenceError
RegExp
RegExp.exec()
RegExp.global
RegExp.ignoreCase
RegExp.lastIndex
RegExp.source
RegExp.test()
RegExp.toString()
String
String.charAt()
String.charCodeAt()
String.concat()
String.fromCharCode()
String.indexOf()
String.lastIndexOf()
String.length
String.localeCompare()
String.match()
String.replace()
String.search()
String.slice()
String.split()
String.substr()
String.substring()
String.toLocaleLowerCase()
String.toLocaleUpperCase()
String.toLowerCase()
String.toString()
String.toUpperCase()
String.trim()
String.valueOf()
SyntaxError
TypeError
undefined
unescape()
URIError

IV. JavaScript 881

JavaScript 883
ApplicationCache
ArrayBuffer
ArrayBufferView
Attr
Audio
BeforeUnloadEvent
Blob
BlobBuilder
Button
Canvas
CanvasGradient
CanvasPattern
CanvasRenderingContext2D
ClientRect
CloseEvent
Comment
Console
ConsoleCommandLine
CSS2Properties
CSSRule
CSSStyleDeclaration
CSSStyleSheet
DataTransfer
DataView
Document
DocumentFragment
DocumentType
DOMException
DOMImplementation
DOMSettableTokenList
DOMTokenList
Element
ErrorEvent
Event
EventSource
EventTarget
FieldSet
File
FileError
FileReader
FileReaderSync
Form
FormControl
FormData
FormValidity
Geocoordinates
Geolocation
GeolocationError
Geoposition
HashChangeEvent
History
HTMLCollection
HTMLDocument
HTMLElement
HTMLFormControlsCollection
HTMLOptionsCollection
IFrame
Image
ImageData
Input
jQuery
KeyEvent
Label
Link
Location
MediaElement
MediaError
MessageChannel
MessageEvent
MessagePort
Meter
MouseEvent
Navigator
Node
NodeList
Option
Output
PageTransitionEvent
PopStateEvent
ProcessingInstruction
Progress
ProgressEvent
Screen
Script
Select
Storage
StorageEvent
Style
Table
TableCell
TableRow
TableSection
Text
TextArea
TextMetrics
TimeRanges
TypedArray
URL
Video
WebSocket
Window
Worker
WorkerGlobalScope
WorkerLocation
WorkerNavigator
XMLHttpRequest
XMLHttpRequestUpload

 1040

JavaScript
JavaScript, -. ,
JavaScript,
, JavaScript,
- . ,
JavaScript .
. ,
, ,
.
. I JavaScript. II
JavaScript: Java
Script, HTML5
-. III
, IV JavaScript. 1
(1.1).
ECMAScript5 (
) HTML5 (
-). ECMAScript5
. , HTML5,
II,
. 11
JavaScript, 12 JavaScript, 19
jQuery 22 HTML5.
,
. ,
, , ,
.
, ,
, .

18


, (
) ( ,
), , , .
,
.
, - .
,
, .
, , ,
. ,
JavaScript,
, ()
, . ,
, , ,
( ).
,
, ,
.

.
, URL .

JavaScript,
CSS HTML ,
.

,
.


.
- :
http://oreilly.com/catalog/9780596805531/
.

. ,

19

.
,
, .
-
OReilly.

.

.
,
, .
, ISBN. :
JavaScript: The Definitive Guide, by David Flanagan (OReilly). Copyright 2011
David Flanagan, 978-0-596-80552-4.

http://oreilly.com/pub/a/oreilly/ask_tim/2001/code
policy.html.
permissions@
oreilly.com.


, .

, -:
http://oreilly.com/catalog/9780596805531
,
, :
bookquestions@oreilly.com
, ,
OReilly -:
http://www.oreilly.com
Facebook: http://facebook.com/oreilly
Twitter:
http://twitter.com/oreillymedia.
YouTube:
http://www.youtube.com/oreillymedia.

, .
, (Mike Loukides),
.
: (Zachary Kessin),

20

, (Raffaele Cecco),
19 <canvas> 21.
,
OReilly: (Dan Fauxsmith),
, (Teresa Elsey), ,
(Rob Romano), , (Ellen Tro
utman Zaig), .

, .
, ,
ECMAScript5, w3c, ,
, JavaScript.
, , ,
JavaScript.

: (Andrew Schulman), (An
gelo Sirigos), c (Aristotle Pagaltzis), (Brendan
Eich), (Christian Heilmann), (Dan Shafer),
. (Dave C. Mitchell), (Deb Cameron), (Do
uglas Crockford), - (Dr. Tankred Hirschmann),
(Dylan Schiemann), (Frank Willison), (Geoff
Stearns), (Herman Venter), (Jay Hodges),
(Jeff Yates), (Joseph Kesselman), (Ken Cooper),
(Larry Sullivan), (Lynn Rollins), (Neil Berk
man), (Nick Thompson), (Norris Boyd),
(Paula Ferguson), - (Peter-Paul Koch), (Philippe
Le Hegaret), (Richard Yaker), (Sanders Kleinfeld),
(Scott Furman), (Scott Issacs), (Shon
Katzenberger), (Terry Allen), (Todd Ditchendorf),
(Vidur Apparao) (Waldemar Horwat).
, -
.
, .
(http://www.davidflanagan.com), 2011

1
1.

JavaScript

JavaScript .
- JavaScript, -
, ,
JavaScript, JavaScript
- .
JavaScript , -
: HTML, -
, CSS, -,
JavaScript, . .
,
, JavaScript , ,
,
-
. JavaScript Java,
Scheme,
Self.
JavaScript.
JavaScript .
, JavaScript
Java. JavaScript ,

. ( )
,
.

22

1. JavaScript

JavaScript:
JavaScript Netscape .
JavaScript ,
Sun Microsystems ( Oracle),
, Netscape ( Mozilla). Netsca
pe
ECMA (European Computer Manufacturers Associ
ation), -
ECMAScript.
- Microsoft
JScript.
JavaScript.
ECMAScript .
-
3 ECMAScript,
:
, -
.
ECMAScript 5,
.
, ECMAScript5,
, ECMAScript3.
, ES3 ES5,
JavaScript, JS.
,
3 5 ECMAScript. (
ECMAScript , -
.)
JavaScript, : JavaScript1.5 JavaScript1.8.
JavaScript,
Mozilla, 1.5
ECMAScript3,
( 11). ,
, Ja
vaScript. , Google
JavaScript V8,
V8 3.0.

- ,
, , API
, . Java
Script ,
, ,
-. ( ,

23

, )
, JavaScript.
- ( 12
JavaScript -).
JavaScript .
JavaScript -
, ,
JavaScript.
API .
, JavaScript
, Array
. JavaScript. ,
JavaScript ,
HTML5 <canvas>,
Canvas .
,
.
, , .
,
:
,
, ,
.
JavaScript
, .

JavaScript
,
, ,
, ,
. JavaScript. ,
- JavaScript,
, , , -.
, JavaScript
HTML-, <script>, HTML-
. ,
,
JavaScript. Firebug
Firefox ( . 1.1 http://
getfirebug.com/) -
-, ,
. Tools (
) Developer Tools ( )

24

1. JavaScript

Web Console (-). ( Firefox4


Web Console, Fire
bug .) ,
, F12
Ctrl-Shift-J.
,
( .1.1),
.

, HTML-,
CSS, ..
JavaScript console ( JavaScript),
JavaScript .
JavaScript,
.
API .
console.log().
,
( ,
) console.log() . ,

alert(),
.

.1.1. Firebug Firefox

25

1.1. JavaScript

1.1. JavaScript
JavaScript,
.
JavaScript: 2
JavaScript, ,
. 3 ,
: JavaScript
, .
, :
// , , .
// : JavaScript.
// - .
// var:
var x; // x.
// =
x = 0; // x 0
x // => 0: .
// JavaScript
x = 1; // .
x = 0.01; // .
x = "hello world"; // .
x = 'JavaScript'; // .
x = true; // .
x = false; // .
x = null; // null - , " ".
x = undefined; // undefined null.

,
JavaScript, .
6 7
, , .
// JavaScript .
// - / .
var book = { // .
topic: "JavaScript", // "topic" "JavaScript".
fat: true // "fat" true.
}; // .
//
book.topic // => "JavaScript"
book["fat"] // => true:
book.author = "Flanagan"; //
book.contents = {}; // {} -

. []:
.
.
.

// JavaScript ( ) :
var primes = [2, 3, 5, 7]; // 4 , [ ].
primes[0] // => 2: ( 0) .
primes.length // => 4: .
primes[primes.length-1] // => 7: .
primes[4] = 9; // .

26

1. JavaScript
primes[4] = 11; // .
var empty = []; // [] - .
empty.length // => 0
// :
var points = [ // 2 .
{x:0, y:0}, // - .
{x:1, y:1}
];
var data = { // 2
trial1: [[1,2], [3,4]], // - .
trial2: [[2,3], [4,5]] // .
};

,

, ,
4 .
JavaScript, ,
. , . []
. , ,
, , , ,
(=>), .
.
JavaScript
, , :
// ()
// . :
3 + 2 // => 5:
3 - 2 // => 1:
3 * 2 // => 6:
3 / 2 // => 1.5:
points[1].x - points[0].x // => 1:
"3" + "2" // => "32": + ,
// JavaScript
var count = 0; //
count++; // 1
count--; // 1
count += 2; // 2: , count = count + 2;
count *= 3; // 3: , count = count * 3;
count // => 6:
//
// , , , ..
// true false.
var x = 2, y = 3; // = ,
x == y // => false:
x != y // => true:
x < y // => true:
x <= y // => true:
x > y // => false:
x >= y // => false:
"two" == "three" // => false:

1.1. JavaScript

27

"two" > "three" // => true: "tw" , "th"


false == (x > y) // => true: false false
//
(x == 2) && (y == 3) // => true: . && - ""
(x > 3) || (y < 3) // => false: . || - ""
!(x == y) // => true: !

JavaScript ,
; 5 .
, , ,
, . (
, ,
.) . ,
, , :
. , ,
( ),
.
.
,
. , ,
.
Ja
vaScript, , .
8 ,
, ,
, .
:
// - JavaScript,
// .
function plus1(x) { // "plus1" "x"
return x+1; // 1
} //
plus1(y) // => 4: y 3, 3+1
var square = function(x) { //
return x*x; //
}; // .
square(plus1(y)) // => 16:

:
// , , .
// JavaScript :
var a = []; //
a.push(1,2,3); // push()
a.reverse(); // :
// . "this" ,
// : points.
points.dist = function() { //
var p1 = this[0]; // ,

28

1. JavaScript
var p2 = this[1]; //
var a = p2.x-p1.x; //
var b = p2.y-p1.y; //
return Math.sqrt(a*a + //
b*b); //
};
points.dist() //

"this"
X
Y

Math.sqrt()
=> 1.414: 2-

, , ,
Java
Script:
// JavaScript ,
// C, C++, Java .
function abs(x) { // ,
if (x >= 0) { // if ...
return x; // , true.
} // if.
else { // else ,
return -x; // false.
} // ,
// 1 .
} // return if/else.
function factorial(n) { //
var product = 1; //
while(n > 1) { //
product *= n; //
n--; //
} //
return product; //
}
factorial(4) //

,
, 1
{}, . ()
product = product * n;
n = n - 1

function factorial2(n) { //
var i, product = 1; //
for(i=2; i <= n; i++) //
product *= i; //
//
return product; //
}
factorial2(5) //

,
1
i 2 n
. {} ,
1

=> 24: 1*4*3*2

=> 120: 1*2*3*4*5

JavaScript - ,
,
. 9 -
JavaScript ;
.
, JavaScript
. , ,
r(),
:
// - Point
function Point(x,y) { //
this.x = x; // this -

1.2. JavaScript

29

this.y = y; //
} //
// , -
// "new"
var p = new Point(1, 1); // (1,1)
// Point
// -, -.
Point.prototype.r = function() {
return Math.sqrt( // x2 + y2
this.x * this.x + // this - Point, ...
this.y * this.y // ... .
);
};
// p Point ( Point) r()
p.r() // => 1.414...

9 , , ,

. 10

. 11
JavaScript
JavaScript. ,
JavaScript -, 12 JavaScript
JavaScript -.

1.2. JavaScript
JavaScript , -
, ,
JavaScript -
. , ,
JavaScript ,
,
.
13 JavaScript - , JavaScript -.
, , JavaScript
HTML- <script>:
<html>
<head>
<script src="library.js"></script> <!-- JavaScript -->
</head>
<body>
<p> HTML</p>
<script>
// JavaScript,
// HTML-
</script>

30

1. JavaScript
<p> HTML.</p>
</body>
</html>

14 Window -
JavaScript.
:
<script>
function moveon() {
// ,
var answer = confirm("Ready to move on?");
// "OK",
if (answer) window.location = "http://google.com";
}
// , , 1 (60000 ).
setTimeout(moveon, 60000);
</script>

, JavaScript
,
. Firebug
( ). HTML , -. , ,
, HTML-.
15
, JavaScript ,
HTML. ,
HTML , HTML- ,

.
:
// .
// , .
function debug(msg) {
// , HTML- id
var log = document.getElementById("debuglog");
// id="debuglog" , .
if (!log) {
log = document.createElement("div"); // <div>
log.id = "debuglog"; // id
log.innerHTML = "<h1>Debug Log</h1>"; //
document.body.appendChild(log); //
}
// <pre> log
var pre = document.createElement("pre"); // <pre>
var text = document.createTextNode(msg); // msg
pre.appendChild(text); // <pre>
log.appendChild(pre); // <pre> log
}

15 , JavaScript HTML-
, -. 16

31

1.2. JavaScript

, JavaScript
CSS, .
HTML- style class:
function hide(e, reflow) { //
if (reflow) { //
e.style.display = "none" //
} //
else { //
e.style.visibility = "hidden"; //
} //
}

e,
2- true,

e ,

function highlight(e) { // e, CSS


// HTML- class.
// , CSS "hilite"
if (!e.className) e.className = "hilite";
else e.className += " hilite";
}

JavaScript HTML-
,
. JavaScript,
,
.
( - ).
,
HTML-.
17 ,
.

HTML-, on.
onclick .
, debug() hide(), ,
debug.js hide.js.
HTML-, <button> onclick,
:
<script
<script
Hello
<button
<button
World

src="debug.js"></script>
src="hide.js"></script>
onclick="hide(this,true); debug('hide button 1');">Hide1</button>
onclick="hide(this); debug('hide button 2');">Hide2</button>

JavaScript,
.
load
click:
// "load" , .
// ,
// JavaScript.
window.onload = function() { //

32

1. JavaScript
// <img>
var images = document.getElementsByTagName("img");
// , "click",
// .
for(var i = 0; i < images.length; i++) {
var image = images[i];
if (image.addEventListener) //
image.addEventListener("click", hide, false);
else // IE8
image.attachEvent("onclick", hide);
}
// - ,
function hide(event) { event.target.style.visibility = "hidden"; }
};

15, 16 17 , JavaScript
(HTML), (CSS) ( ) -.
, ,
,
.
JavaScript
, .
jQuery, 19 jQuery.
jQuery
, .
,
, IE6.
, jQuery,
$(). , debug(),
, jQuery:
function debug(msg) {
var log = $("#debuglog"); // msg.
if (log.length == 0) { // , ...
log = $("<div id='debuglog'><h1>Debug Log</h1></div>");
log.appendTo(document.body); // .
}
log.append($("<pre/>").text(msg)); // msg <pre>
} // log

,
-. . , -
, ,
JavaScript. -
,
, -
. 18 HTTP , JavaScript
HTTP- .
20 ,
( )

1.2. JavaScript

33

. 21
,
HTML-
<canvas>. , 22 HTML5
-,
HTML5. , ,
, , ,
. ,
,
JavaScript.
, ,
, .

1.2.1. : JavaScript
,

JavaScript ( HTML CSS). 1.1
(.1.2).

.1.2. -

1.1.
,
,
-.
JavaScript,
JavaScript:

34

1. JavaScript

.
.
.
.
HTTP-.
<canvas>.
1.1. JavaScript
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Loan Calculator</title>
<style> /* CSS: */
.output { font-weight: bold; } /* */
#payment { text-decoration: underline; } /* id="payment" */
#graph { border: solid black 1px; } /* */
th, td { vertical-align: top; } /* */
</style>
</head>
<body>
<!- HTML- <input>, ,
<span>, . ,
"interest" "years". JavaScript-,
. ,
"onchange" "onclick".
JavaScript-, .
-->
<table>
<tr><th>Enter Loan Data:</th>
<td></td>
<th>Loan Balance, Cumulative Equity, and Interest Payments</th></tr>
<tr><td>Amount of the loan ($):</td>
<td><input id="amount" onchange="calculate();"></td>
<td rowspan=8>
<canvas id="graph" width="400" height="250"></canvas></td></tr>
<tr><td>Annual interest (%):</td>
<td><input id="apr" onchange="calculate();"></td></tr>
<tr><td>Repayment period (years):</td>
<td><input id="years" onchange="calculate();"></td>
<tr><td>Zipcode (to find lenders):</td>
<td><input id="zipcode" onchange="calculate();"></td>
<tr><th>Approximate Payments:</th>
<td><button onclick="calculate();">Calculate</button></td></tr>
<tr><td>Monthly payment:</td>
<td>$<span class="output" id="payment"></span></td></tr>
<tr><td>Total payment:</td>
<td>$<span class="output" id="total"></span></td></tr>
<tr><td>Total interest:</td>
<td>$<span class="output" id="totalinterest"></span></td></tr>
<tr><th>Sponsors:</th><td colspan=2>
Apply for your loan with one of these fine lenders:

1.2. JavaScript

35

<div id="lenders"></div></td></tr>
</table>
<!-- - JavaScript- <script> . -->
<!-- , <head>, -->
<!-- , JavaScript- HTML-. -->
<script>
"use strict"; // ECMAScript 5,
/*
* calculate(),
* HTML . <input>,
* , <span>. ,
* , .
*/
function calculate() {
//
var amount = document.getElementById("amount");
var apr = document.getElementById("apr");
var years = document.getElementById("years");
var zipcode = document.getElementById("zipcode");
var payment = document.getElementById("payment");
var total = document.getElementById("total");
var totalinterest = document.getElementById("totalinterest");
// . ,
// .
// .
// .
var principal = parseFloat(amount.value);
var interest = parseFloat(apr.value) / 100 / 12;
var payments = parseFloat(years.value) * 12;
// .
var x = Math.pow(1 + interest, payments); // Math.pow()
var monthly = (principal*x*interest)/(x-1);
// , ,
//
if (isFinite(monthly)) {
// , 2
payment.innerHTML = monthly.toFixed(2);
total.innerHTML = (monthly * payments).toFixed(2);
totalinterest.innerHTML = ((monthly*payments)-principal).toFixed(2);
// ,
//
save(amount.value, apr.value, years.value, zipcode.value);
// :
// ,
try { // ,
getLenders(amount.value, apr.value, years.value, zipcode.value);
}
catch(e) { /* */ }
// ,
// ,
chart(principal, interest, monthly, payments);

36

1. JavaScript
}
else {
// ,
// , .
// , .
payment.innerHTML = ""; //
total.innerHTML = ""
totalinterest.innerHTML = "";
chart(); //
}
}
// localStorage.
// . (,
// Firefox) ,
// URL file://. HTTP.
function save(amount, apr, years, zipcode) {
if (window.localStorage) { // ,
localStorage.loan_amount = amount;
localStorage.loan_apr = apr;
localStorage.loan_years = years;
localStorage.loan_zipcode = zipcode;
}
}
// .
window.onload = function() {
// localStorage
if (window.localStorage && localStorage.loan_amount) {
document.getElementById("amount").value = localStorage.loan_amount;
document.getElementById("apr").value = localStorage.loan_apr;
document.getElementById("years").value = localStorage.loan_years;
document.getElementById("zipcode").value = localStorage.loan_zipcode;
}
};
// , ()
// , .
//
// . , .
function getLenders(amount, apr, years, zipcode) {
// XMLHttpRequest,
if (!window.XMLHttpRequest) return;
//
var ad = document.getElementById("lenders");
if (!ad) return; // ,
// URL
var url = "getLenders.php" + // URL
"?amt=" + encodeURIComponent(amount) + //
"&apr=" + encodeURIComponent(apr) + //
"&yrs=" + encodeURIComponent(years) +
"&zip=" + encodeURIComponent(zipcode);
// URL XMLHttpRequest
var req = new XMLHttpRequest(); //
req.open("GET", url); // HTTP GET url

1.2. JavaScript

37

req.send(null); //
// ,
// HTTP- .
// JavaScript.
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
// , , HTTP-
var response = req.responseText; // HTTP-
var lenders = JSON.parse(response); // JS-
// lender HTML-
var list = "";
for(var i = 0; i < lenders.length; i++) {
list += "<li><a href='" + lenders[i].url + "'>" +
lenders[i].name + "</a>";
}
// HTML- ,
// .
ad.innerHTML = "<ul>" + list + "</ul>";
}
}
}
// , ,
// HTML- <canvas>.
// , .
function chart(principal, interest, monthly, payments) {
var graph = document.getElementById("graph"); // <canvas>
graph.width = graph.width; // canvas
//
// <canvas>, .
if (arguments.length == 0 || !graph.getContext) return;
// "" <canvas>,
//
var g = graph.getContext("2d"); //
var width = graph.width, height = graph.height; //
//
//
function paymentToX(n) { return n * width/payments; }
function amountToY(a) { return height-(a*height/(monthly*payments*1.05));}
// - (0,0) (payments,monthly*payments)
g.moveTo(paymentToX(0), amountToY(0)); //
g.lineTo(paymentToX(payments), //
amountToY(monthly*payments));
g.lineTo(paymentToX(payments), amountToY(0)); //
g.closePath(); //
g.fillStyle = "#f88"; // -
g.fill(); //
g.font = "bold 12px sans-serif"; //
g.fillText("Total Interest Payments", 20,20); //
//
//

38

1. JavaScript
var equity = 0;
g.beginPath(); //
g.moveTo(paymentToX(0), amountToY(0)); //
for(var p = 1; p <= payments; p++) {
//
var thisMonthsInterest = (principal-equity)*interest;
equity += (monthly - thisMonthsInterest); // - .
g.lineTo(paymentToX(p),amountToY(equity)); //
}
g.lineTo(paymentToX(payments), amountToY(0)); // X
g.closePath(); // .
g.fillStyle = "green"; //
g.fill(); // .
g.fillText("Total Equity", 20,35); //
// , ,
var bal = principal;
g.beginPath();
g.moveTo(paymentToX(0),amountToY(bal));
for(var p = 1; p <= payments; p++) {
var thisMonthsInterest = bal*interest;
bal -= (monthly - thisMonthsInterest); //
g.lineTo(paymentToX(p),amountToY(bal)); //
}
g.lineWidth = 3; //
g.stroke(); //
g.fillStyle = "black"; //
g.fillText("Loan Balance", 20,50); //
// X
g.textAlign="center"; //
var y = amountToY(0); //
for(var year=1; year*12 <= payments; year++) { //
var x = paymentToX(year*12); //
g.fillRect(x-0.5,y-3,1,3); //
if (year == 1) g.fillText("Year", x, y-5); //
if (year % 5 == 0 && year*12 !== payments) //
g.fillText(String(year), x, y-5);
}
//
g.textAlign = "right"; //
g.textBaseline = "middle"; //
var ticks = [monthly*payments, principal]; //
var rightEdge = paymentToX(payments); //
for(var i = 0; i < ticks.length; i++) { //
var y = amountToY(ticks[i]); //
g.fillRect(rightEdge-3, y-0.5, 3,1); //
g.fillText(String(ticks[i].toFixed(0)), //
rightEdge-5, y);
}
}
</script>
</body>
</html>

.






Y X




5




X Y
2
Y

.

I
I.

JavaScript

2 12, Ja
vaScript JavaScript.
, , , ,
.
2
3 ,
4
5
6
7
8
9
10
11 JavaScript
12 JavaScript

2
2.


, , .
; , ,
, ,
. JavaScript.

2.1.
JavaScript .
ASCII Latin-1
, . ECMA
Script3 , JavaScript
2.1 , ECMAScript5 ,
3 .
JavaScript 3.2.

2.1.1.
JavaScript , . ,
,

. , while while, Whi
le WHILE. online, Online, OnLine ONLINE
.
, , HTML ( XHTML)
. HTML JavaScript ,
. JavaScript-
, HTML, .
HTML , Java
Script . ,

42

2.

onclick HTML onClick, Ja


vaScript- ( XHTML-) onclick.

2.1.2. ,

JavaScript ,
. , JavaScript
( ,
2.5).

.
(\u0020) JavaScript
: (\u0009),
(\u000B), (\u000C), (\u00A0),
(\uFEFF), ,
Zs. JavaScript
: (\u000A), (\u000D),
(\u2028) (\u2029).

.
, ( Cf), RIGHTTO-LEFT MARK (\u200F) LEFT-TO-RIGHT MARK (\u200E),
, .

JavaScript,
, (
), JavaScript. ZERO
WIDTH JOINER (\u200D) ZERO WIDTH NON-JOINER (\u200C),
,
. ,
(\uFEFF) .

2.1.3.

.
, , JavaScript
, ASCII,
16- .
\u,
( AF ,
).
JavaScript,
( ).
e, , \u00E9, Java
Script :
"cafe" === "caf\u00e9" // => true

43

2.2.


, ,
ASCII
.

2.1.4.
.
e,
,
\u00E9 ASCII- e,
\u0301.
,
.

,
. JavaScript ,
,
, .

2.2.
JavaScript .
//
JavaScript. /* */
. ,
. Ja
vaScript-:
// .
/* */ // .
/*
* .
* .
*/

2.3.
, .
:
12 //
1.2 //
"hello world" //
'Hi' //
true //
false //
/javascript/gi //
null //







" " ( )

3.
10.

44

2.

( 4.2),
:
{ x:1, y:2 } //
[1,2,3,4,5] //

2.4.

. JavaScript
, .
JavaScript ,
(_) ($). , ,
. ( ,
.)
:
i
my_variable_name
v13
_dummy
$str


ASCII . JavaScript

. ( ECMAScript
Mn, Mc Pc
, .)

:
var s = true;
var = 3.14;

, JavaScript
.
. .

2.4.1.
JavaScript ,
.
:
break
case
catch
continue
debugger
default

delete
do
else
false
finally
for

function
if
in
instanceof
new
null

return
switch
this
throw
true
try

typeof
var
void
while
with

45

2.4.

JavaScript ,
,
. ECMAScript5 :
class

const

enum

export

extends

import

super

,
JavaScript :
implements

let

private

public

interface

package

protected

static

yield


.
, ,
:
arguments

eval

ECMAScript3 Java, ,
ECMAScript5,
,
JavaScript- JavaScript,
ECMAScript3:
abstract

double

goto

native

static

boolean

enum

implements

package

super

byte

export

import

private

synchronized

char

extends

int

protected

throws

class

final

interface

public

transient

const

float

long

short

volatile

JavaScript
,
:
arguments

encodeURI

Infinity

Number

RegExp

Array

encodeURIComponent

isFinite

Object

String

Boolean

Error

isNaN

parseFloat

SyntaxError

Date

eval

JSON

parseInt

TypeError

decodeURI

EvalError

Math

RangeError

undefined

decodeURIComponent

Function

NaN

ReferenceError

URIError

, JavaScript
. ,
JavaScript (, )
. Window
,
JavaScript.

46

2.

2.5.
, (5)
JavaScript (;).

:
. JavaScript
, .
(
}.)
JavaScript
( ),
. ,
, ,
. ,
Java
Script.
.
, :
a = 3;
b = 4;

, ,
:
a = 3; b = 4;

, JavaScript
:
,
.
( , ), JavaScript
,
.
:
var a
a
=
3
console.log(a)

JavaScript , :
var a; a = 3; console.log(a);

JavaScript
, var a a
. a
a;, JavaScript
,
a = 3;.

2.5.

47

,
, .
, :
var y = x + f
(a+b).toString()


f , JavaScript
, :
var y = x + f(a+b).toString();

, .
,
.
, (, [, /, + -, ,

. , /, + -,
, , ( [,
, ,
JavaScript.
,
,
:
var x = 0 //
;[x,x+1,x+2].forEach(console.log) // ;
//

, JavaScript
,
, .
return, break continue (5).
,
.
( ), JavaScript
. , :
return
true;

JavaScript ,
:
return; true;

, , :
return true;

,
return, break continue , .
, , ,
, .

48

2.

++ -- (4.8).
, .. , ,
.. .
,
, , .
,
++ -- ,
, . , :
x
++
y

x; ++y;, x++; y.

3
3.

,
3,14 Hello World. ,
,
,
.
, ,
( ) .

.
.
, JavaScript.
, , ,
1.1.
.
JavaScript :
. JavaScript ,
( ) (
) .
(3.1) (3.2) .
3.3.
null undefined ,
, , .
.
null undefined 3.4.
JavaScript, , ,
null undefined, .
(.. ) ,
( ,
, ). 3.5
, , 6.

50

3. ,

JavaScript
. , JavaScript
, ,
. JavaScript
. ,
, .
7.
JavaScript ,
. , .

. , ,
, JavaScript .
JavaScript ,
, JavaScript
, .
8.
,
( new), .
,
. .
Array Function JavaScript
. Date , . RegExp
, (
, 10). Error
,
, JavaScript.
,
-. 9.
JavaScript .
, ,

.
(..
) ,
, .
JavaScript - .
,
.
, a,
a sort(). sort() a:
a.sort(); // - sort(a).

9.
JavaScript . ,
,
( 3.6). null undefined
JavaScript, .

3.1.

51

JavaScript .
. ,
.
. :
JavaScript
. , , null undefined
, ,
. ,
, . JavaScript
:
, JavaScript
.
, 3.7.
JavaScript
. , ,
, .
, ,
.
3.8.
JavaScript , ==
, 3.8.1.
JavaScript :

.
var. JavaScript .
, ,
. ,
,
.
3.9 3.10.

3.1.
, JavaScript
. JavaScript
( ).
JavaScript 64- ,
IEEE 754.1
1,7976931348623157 10308 5 10-324.
JavaScript
9007199254740992 (253) 9007199254740992 (253)
.
. , JavaScript
1

Java double.
double
C C++.

52

3. ,

( ,
4) 32- .
, JavaScript,
. JavaScript
, . ,
(-),
.
(. 4),
.

3.1.1.
JavaScript
. :
0
3
10000000

JavaScript
( 16).
0x 0X,
. 0 9
a ( A) f ( F), 10 15.
:
0xff // 15*16 + 15 = 255 ( 10)
0xCAFE911

ECMAScript
( 8), JavaScript
. 0,
0 7. :
0377 // 3*64 + 7*8 + 7 = 255 ( 10)

,
, ,
,
. (strict) ,
ECMAScript 5 ( 5.7.3),
.

3.1.2.


. ,
.

: , e ( E),
.

53

3.1.

, 10 ,
.
:
[][.][(E|e)[(+|-)]]

:
3.14
2345.789
.333333333333333333
6.02e23 // 6.02 1023
1.4738223E-32 // 1.4738223 10-32

3.1.3. JavaScript
JavaScript
. : +,
-, *, /
% ( ).
4.
JavaScript
, ,
Math:
Math.pow(2,53) //
Math.round(.6) //
Math.ceil(.6) //
Math.floor(.6) //
Math.abs(-5) //
Math.max(x,y,z) //
Math.min(x,y,z) //
Math.random() //
Math.PI //
Math.E //
Math.sqrt(3) //
Math.pow(3, 1/3) //
Math.sin(0) //
Math.log(10) //
Math.log(100)/Math.LN10 //
Math.log(512)/Math.LN2 //
Math.exp(3) //

=> 9007199254740992: 2 53
=> 1.0:
=> 1.0:
=> 0.0:
=> 5:


x, 0 <= x < 1.0
: /
e:
3
3
: Math.cos, Math.atan .
10
100 10 ()
512 2
Math.E

, Java
Script, Math.
JavaScript
, .

(), ,
JavaScript Infinity. ,

, ,
-Infinity. ,

54

3. ,

, , : , ,

(, ).
,
, .
0.
, ,
.
, JavaScript
.
JavaScript:
.
:
,
(not-a-number), NaN. NaN
,

,
.
JavaScript Infinity NaN,
.
ECMAScript3 /
. ECMAScript 5 ,
. Number
,
ECMAScript3. :
Infinity //
//
Number.POSITIVE_INFINITY //
1/0 //
Number.MAX_VALUE + 1 //

, /,
Infinity.
, .
.
Infinity.

Number.NEGATIVE_INFINITY // .
-Infinity
-1/0
-Number.MAX_VALUE - 1
NaN //
//
Number.NaN //
0/0 //

, /,
NaN.
, , .
NaN.

Number.MIN_VALUE/2 // : 0
-Number.MIN_VALUE/2 //
-1/Infinity //
-0

JavaScript :
,
. ,

55

3.1.

x == NaN, , x NaN.
x != x. true
, x NaN.
isNaN(). true,
NaN ,
. isFinite() true,
, NaN, Infinity -Infinity.
.
( )
,
, , :
var zero = 0; //
var negz = -0; //
zero === negz //
1/zero === 1/negz //



=> true:
=> false: Infinity -Infinity

3.1.4.

,
JavaScript
(, 18437736874454810627). ,
JavaScript
.
IEEE-754, Java
Script ( ),
,
, 1/2, 1/8 1/1024. ,
(
), 1/10, 1/100 ..
, 0.1.
JavaScript
0.1. ,
, .
:
var x = .3 - .2; //
var y = .2 - .1; //
x == y //
x == .1 //
y == .1 //


10
=> false: !
=> false: .3-.2 .1
=> true: .2-.1 .1

- .3 .2
.2 .1. ,
- JavaScript:
,
. , , x y
.

56

3. ,

:
.
JavaScript ,
, .

. ,
, .

3.1.5.
JavaScript Date() ,
. Date
. Date
, .
. :
var
var
var
var

then = new Date(2010, 0, 1); //


later = new Date(2010, 0, 1, 17, 10, 30); //
now = new Date(); //
elapsed = now - then; //

later.getFullYear() //
later.getMonth() //
later.getDate() //
later.getDay() //
later.getHours() //
later.getUTCHours() //
later.toString() //
later.toUTCString() //
later.toLocaleDateString() //
later.toLocaleTimeString() //
later.toISOString() //

2010
, 17:10:30

:
=> 2010
=> 0:
=> 1:
=> 5: . 0 - ., 5 - .
=> 17: 17
UTC;
=> "Fri Jan 01 2010 17:10:30 GMT+0300"
=> "Fri, 01 Jan 2010 14:10:30 GMT"
=> "1 2010 ."
=> "17:10:30"
=> "2010-01-01T14:10:30.000Z"

3.2.
, 16-
, . Java
Script , .
16- , .
( ) JavaScript
: 16- 0, 1 ..
, 0. JavaScript
.
16-
, 1.

3.2.1.
JavaScript-,
(' ").
,

57

3.2.

, ,
.
:
"" // :
'testing'
"3.14"
'name="myform"'
" O'Reilly, ?"
" \n "
" "

ECMAScript3
. ECMAScript5
, ,
, (\).
, ,
.
, \n ( ):
"\n" // ,
"\ // , . ECMAScript5
\
"

, JavaScript
JavaScript
UTF-16, JavaScript
16- .
( )
, 16 ,
. ,
16 ,
UTF-16 ( )
16- . , JavaScript,
, 2 ( 16- ),
:
var p = ""; //
var e = "e"; //
p.length //
e.length //
//

- 1 16- 0x03c0
e - 1 17- 0x1d452
=> 1: p 16-
=> 2: UTF-16 e
16- : "\ud835\udc52"

, JavaScript,
16- , .
,
,
UTF-16.

58

3. ,

, , ,
,
,
, , cant OReillys.
, (\)
, (
).
JavaScript HTML-, HTML, , JavaScript-. JavaScript,
HTML ,
. JavaScript- HTML-
JavaScript, HTML.
JavaScript-
, , ,
HTML- :
<button onclick="alert('')"> </button>

3.2.2.

(\) JavaScript-.
, , ,
. , \n
(escape sequence), .
, , \',
.
,
. ,

.
, :
'You\'re right, it can\'t be a quote'

.3.1 JavaScript
.
;
Latin-1 Unicode
. , \xA9 ,
Latin-1 A9.
, \u,
, .
, \u03c0 .
\ ,
.3.1, ( ,
, ). , \#
, #. , , ECMAScript5

.

59

3.2.
3.1. JavaScript

\0

NUL (\u0000)

\b

(\u0008)

\t

(\u0009)

\n

(\u000A)

\v

(\u000B)

\f

(\u000C)

\r

(\u000D)

\"

(\u0022)

\'

(\u0027)

\\

(\u005C)

\xXX

Latin-1, XX

\uxXXXX

Unicode,
XXXX

3.2.3.
JavaScript
. + , ,
,
. :
msg = "Hello, " + "world"; // "Hello, world"
greeting = " ," + " " + name;

16-
length. , s
:
s.length

, length (
, ):
var s = "hello, world" // .
s.charAt(0) // => "h": .
s.charAt(s.length-1) // => "d": .
s.substring(1,4) // => "ell": 2-, 3- 4- .
s.slice(1,4) // => "ell":
s.slice(-3) // => "rld": 3
s.indexOf("l") // => 2: l.
s.lastIndexOf("l") // => 10: l.
s.indexOf("l", 3) // => 3: "l",
// 3
s.split(", ") // => ["hello", "world"]
s.replace("h", "H") // => "Hello, world":
s.toUpperCase() // => "HELLO, WORLD"

60

3. ,

, JavaScript . ,
replace() toUpperCase() : ,
.
ECMAScript5 ,
, charAt()
(16- )
:
s = "hello, world";
s[0] // => "h"
s[s.length-1] // => "d"

-, Mozilla, Firefox,
. (
IE) Mozilla ,
ECMAScript5.

3.2.4.
JavaScript RegExp(),
, .
,
JavaScript Perl. , RegExp ,

.
RegExp JavaScript.
Date,
.
.
10. RegExp
,
.
RegExp
,
JavaScript. ,
, .
,
. :
/^HTML/ //
/[1-9][0-9]*/ //
/\bjavascript\b/i //
//

H T M L
, ,
"javascript"
,

RegExp . ,
, RegExp .
:
var text = "testing: 1, 2, 3"; //
var pattern = /\d+/g //
pattern.test(text) //
text.search(pattern) //



=> true:
=> 9:

3.3.

61

text.match(pattern) // => ["1", "2", "3"]:


text.replace(pattern, "#"); // => "testing: #, #, #"
text.split(/\D+/); // => ["","1","2","3"]:

3.3.
-.
.
true false.

, JavaScript-. :
a == 4

, a 4. ,
true.
a 4, false.
Java
Script. , if/else JavaScript ,
true, , false. ,
, ,
. :
if (a == 4)
b = b + 1;
else
a = a + 1;

a 4.
, b 1; 1
a.
3.8, JavaScript
.
( ) false:
undefined
null
0
-0
NaN
"" //

, (),
( ) true. false
, ,
, . ,
JavaScript ,
false, true.
, o
null. o
null, :

62

3. ,
if (o !== null) ...

!== o null
true false.
, null , :
if (o) ...

if ,
o null. :
if , o false
( null undefined). if
, ,
o. null 0 "",
.
toString(),
true false,
. ,
.
&& .
,
. || :
, ( ) ,
. ,
! : true
false . :
if ((x == 0 && y == 0) || !(z == 0)) {
// x y 0 z
}

4.10.

3.4. null undefined


null JavaScript
. typeof
null object, , null
. null

, , .
,
null JavaScript: null nil.
JavaScript ,
. undefined, -
. ,
,
. , undefined ,
,
, . undefined

3.5.

63

(
, null), undefined. ECMAScript3
undefined , /,
. ECMAScript5,
JavaScript, ,
undefined . typeof undefined
undefined, ,
.
, , null undefined,
. ==
. ( ,
===.)
false. null, undefined
- . . [],
, TypeError.
undefined
- , null
.

, null.

3.5.
Java
Script. ,
, . ,
. Java
Script, :
,
JavaScript. JavaScript ( ), ,
, :
, undefined, Infinity NaN;
, isNaN(), parseInt() (3.8.2) eval() (
4.12);
-, Date(), RegExp(), String(), Object() Array()
(3.8.2);
, Math JSON (6.9).

, .
2.4.1.
.
. ,
JavaScript ,
Global. JavaScript Window,
,
JavaScript.

64

3. ,

, .. JavaScript-,
,
this:
var global = this; //

JavaScript JavaScript-,
, Window.
window, ,
this .
Window ,
, - JavaScript.

JavaScript.
.
, .
3.10.2.

3.6. -
JavaScript :
, .
. ,
, .
m o, o.m().
, :
var s = "hello world!"; //
var word = s.substring(s.indexOf(" ")+1, s.length); //

, ?

s, JavaScript ,
new String(s). ( 6.2.2)
.
. (

, ,
.)

: -
Number() Boolean(),
. null undefined -:
TypeError.
,
:
var s = "test"; // .
s.len = 4; // .
var t = s.len; // .

3.7.

65

t undefined.
String, len 4
. (
) String len.
,
undefined. ,
- ( )
. ,
:
.
, ,
, -,
String
Number Boolean. -
.
, ,
,
.
, (
) -
String(), Number() Boolean():
var
var
var
var

s
S
N
B

=
=
=
=

"test", n = 1, b = true; //
new String(s); //
new Number(n); //
new Boolean(b); //

, .
String
Number
Boolean

JavaScript
-, .. S, N B ,
, , s, n b.
==
-, === . typeof
-.

3.7.

(undefined, null, ,
) ( ) JavaScript
. :
( ).

. .
,
. JavaScript
, , , ,
, .
:

66

3. ,
var s = "hello"; //
s.toUpperCase(); // "HELLO", s
s // => "hello":

, :
, . ,
, null undefined :
.
. JavaScript
,
.
. -,
:
var o = { x:1 }; //
o.x = 2; // ,
o.y = 3; // ,
var a = [1,2,3] //
a[0] = 0; //
a[3] = 4; //

: ,
.
,
, :
var o
o ===
var a
a ===

= {x:1}, p = {x:1}; //
p //
= [], b = []; //
b //


=> false:

=> false:

JavaScript,
. ,
, , :
,
.
var a = []; //
var b = a; //
b[0] = 1; //
a[0] //
a === b //

a .
b .
b.
=> 1: a.
=> true: a b , .

, ( )
: .
,
.
for (5.5.3):
var a = ['a','b','c']; //
var b = []; //
for(var i = 0; i < a.length; i++) { //
b[i] = a[i]; //
}


,
a[]
a[] b[]

67

3.8.

, ,
.
, :
function equalArrays(a,b) {
if (a.length != b.length) return false; //
for(var i = 0; i < a.length; i++) //
if (a[i] !== b[i]) return false; //
//
return true; //
}

3.8.
JavaScript .
: , Java
Script ,
JavaScript .
( ) true, (
) false. :
, .
,
(
NaN). :
10 + " objects" //
"7" * "4" //
var n = 1 - "x"; //
n + " objects" //

=>
=>
=>
=>

"10 objects". 10
28:
NaN: "x"
"NaN objects": NaN "NaN"

.3.2 , JavaScript
. ,
, .
, .
, .3.2,
.
3.3. .
. ,
, .
,
, ,
NaN.
: true
1, false "" 0.
:
-
(3.6), String(), Number() Boolean().
null undefined:
, ,
TypeError.

68

3. ,


3.8.3.
3.2. JavaScript

undefined

"undefined"

NaN

false


TypeError

null

"null"

false


TypeError

true

"true"

false

"false"

new Boolean(true)
new Boolean(false)

"" ( )

false

new String("")

"1.2" ( , )

1.2

true

new String("1.2")

"one" ( ,
)

NaN

true

new String("one")

"0"

false

new Number(0)

-0

"0"

false

new Number(-0)

NaN

"NaN"

false

new Number(NaN)

Infinity

"Infinity"

true

new Number(Infinity)

-Infinity

"-Infinity"

true

new Number(-Infinity)

1 (, )

"1"

true

new Number(1)

{} ( )

. . 3.8.3 .
3.8.3

true

[] ( )

""

true

[9] (1 )

"9"

true

['a'] ( )

NaN
join()

true

function(){} ( ) . . 3.8.3 NaN

true

3.8.1.
JavaScript ==
. ,
true:
null == undefined //
"0" == 0 //
0 == false //
"0" == false //

.
.
. .
.

4.9.1 , ==,
, ,
===,
.

3.8.

69

,
. , ,
undefined, false.
, undefined == false. JavaScript

. if undefined false, ==
.

3.8.2.
JavaScript
,
,
.

Boolean(), Number(), String() Object(). ,
- (3.6).
new
, .3.2:
Number("3") //
String(false) //
Boolean([]) //
Object(3) //

=>
=>
=>
=>

3
"false" false.toString()
true
new Number(3)

, , null undefined,
toString(), ,
String(). , , .3.2
, null undefined
TypeError. Object()
, .
JavaScript
.
+ ,
. + . !
.
,
:
x + "" // , String(x)
+x // , Number(x). x-0
!!x // , Boolean(x). !

,
, JavaScript
,
.
toString() Number ,
.
, .

70

3. ,

(
2 36). :
var n = 17;
binary_string = n.toString(2); // "10001"
octal_string = "0" + n.toString(8); // "021"
hex_string = "0x" + n.toString(16); // "0x11"




.
Number . toFixed()
, .
.
toExponential()
, ,
(..
, ). toPrecision()
, .

,
. ,
, . :
var n = 123456.789;
n.toFixed(0); //
n.toFixed(2); //
n.toFixed(5); //
n.toExponential(1); //
n.toExponential(3); //
n.toPrecision(4); //
n.toPrecision(7); //
n.toPrecision(10); //

"123457"
"123456.79"
"123456.78900"
"1.2e+5"
"1.235e+5"
"1.235e+5"
"123456.8"
"123456.7890"

Number(),
.

, . parseInt()
parseFloat() ( , - )
. parseInt() ,
parseFloat() ,
, . 0x
0X, parseInt()
.1 , parseInt() parseFloat(),
1

ECMAScript 3 parseInt()
, 0 ( 0x 0X),
. ,
parseInt() , 0,
! ECMAScript5 parseInt()
,
8 .

71

3.8.

,
, .
,
NaN:
parseInt("3 blind mice") //
parseFloat(" 3.14 meters") //
parseInt("-12.34") //
parseInt("0xFF") //
parseInt("0xff") //
parseInt("-0XFF") //
parseFloat(".1") //
parseInt("0.1") //
parseInt(".1") //
parseFloat("$72.47"); //

=>
=>
=>
=>
=>
=>
=>
=>
=>
=>

3
3.14
-12
255
255
-255
0.1
0
NaN: "."
NaN: "$"

parseInt() ,
.
2 36. :
parseInt("11", 2); //
parseInt("ff", 16); //
parseInt("zz", 36); //
parseInt("077", 8); //
parseInt("077", 10); //

=>
=>
=>
=>
=>

3 (1*2 + 1)
255 (15*16 + 15)
1295 (35*36 + 35)
63 (7*8 + 7)
77 (7*10 + 7)

3.8.3.
:
( ) true.
-: new Boolean(false)
, , true.

. ,
JavaScript ,
, .
, ,
, JavaScript.
(, -)
.
.
toString(), .
toString() (
, 6.4):
({x:1, y:2}).toString() // => "[object Object]"

toString().
, toString() Array
, .
toString() Function ,
.
JavaScript.

72

3. ,

Date toString(),
( JavaScript).
RegExp toString(), RegExp ,
:
[1,2,3].toString() //
(function(x) { f(x); }).toString() //
/\d+/g.toString() //
new Date(2010,0,1).toString() //

=>
=>
=>
=>

"1,2,3"
"function(x) {\n f(x);\n}"
"/\\d+/g"
"Fri Jan 01 2010 00:00:00 GMT+0300"

valueOf().
: ,
, .
,
,
valueOf() , .
- valueOf(),
. ,
. valueOf() .
Date valueOf(),
: , 1 1970:
var d = new Date(2010, 0, 1); // 1 2010 , ( )
d.valueOf() // => 1262293200000

, toString() valueOf(),
. ,
, JavaScript
.
.
JavaScript
:
toString(), .
, (
) .
,
.3.2.
toString()
, valueOf().
, .
, (
) .
, toString(), valueOf()
TypeError.
,
valueOf():
valueOf(), ,
( )
.

3.8.

73

, toString(), ,

.
TypeError.

,
0,
. valueOf(),
, ,
toString().
. 0.
,
. ,
, .
+ JavaScript .
- , JavaScript
,
,
. ==.
,
.
, + ==,
Date. Date
JavaScript,
, . ,
, (
valueOf()), Date
( toString()).
, : ,
valueOf() toString(), ,
.
<
==, Date:
valueOf(),
toString(). , ,
, .
+, ==, != ,
.

Date. -, ,
. +, -, ==
> Date:
var now = new Date(); //
typeof (now + 1) //
typeof (now - 1) //
now == now.toString() //
now > (now -1) //

Date
=> "": +
=> "": -
=> true:
=> true: > Date

74

3. ,

3.9.
JavaScript, .
var :
var i;
var sum;

var,
:
var i, sum;

:
var message = "hello";
var i = 0, j = 0, k = 0;

var ,
, (undefined),
.
, var for
for/in ( 5),
. :
for(var i = 0; i < 10; i++) console.log(i);
for(var i = 0, j=10; i < 10; i++,j--) console.log(i*j);
for(var p in o) console.log(p);


, C Java, ,
JavaScript .
JavaScript . , JavaScript
,
:
var i = 10;
i = "ten";

3.9.1
var
. ,
.
, JavaScript
. , ECMAScript5
(5.7.3),
.
, ,
var, JavaScript ,
( ,
3.10.2), . ,
.

75

3.10.

,
var.

3.10.
(scope) ,
.
JavaScript-.
, , .
.
,
.

.
, ,
:
var scope = "global"; //
function checkscope() {
var scope = "local"; //
return scope; //
}
checkscope() //



,
=> "local"

, var
,
var. , , :
scope = "global"; // , var.
function checkscope2() {
scope = "local"; // ! .
myscope = "local"; // . .
return [scope, myscope]; // .
}
checkscope2() // => ["local", "local"]: !
scope // => "local": .
myscope // => "local": .

.
,
. :
var scope = "global scope"; //
function checkscope() {
var scope = "local scope"; //
function nested() {
var scope = "nested scope"; //
return scope; //
}
return nested();
}
checkscope() //




scope

=> "nested scope"

76

3. ,

3.10.1.
C-
,
, , .
,
JavaScript. JavaScript ,
: , ,
, , ,
.
i, j k ,

:
function test(o) {
var i = 0; //
if (typeof o == "object") {
var j = 0; //
for(var k=0; k < 10; k++) { //
console.log(k); //
}
console.log(k); //
}
console.log(j); //
}

i
j ,
k ,
0 9
k - : 10
j ,

JavaScript ,
, , .
, ,
. JavaScript :
JavaScript ,
( )
. :
var scope = "global";
function f() {
console.log(scope); // "undefined", "global"
var scope = "local"; // ,
console.log(scope); // "local"
}

,
global, var
.
.
, ,
.
,
var. ,
, ,
, :

3.10.
function f() {
var scope; //
console.log(scope); //
scope = "local"; //
console.log(scope); //
}

77


, "undefined"

, ,
,
, . Ja
vaScript ,
, ,
.
.

3.10.2.
JavaScript
(3.5).
var, (
6.7), .. , delete.
,
, JavaScript
. ,
, ,
:
var truevar = 1; //
fakevar = 2; //
this.fakevar2 = 3; //
delete truevar //
delete fakevar //
delete this.fakevar2 //

, .
.
.
=> false:
=> true:
=> true:

JavaScript
, ECMAScript.
,
,
. ECMAScript3
(call object), ECMAScript5
(declarative environment record). JavaScript
this,
,
. ,
, .

, .

78

3. ,

3.10.3
JavaScript :

, .
.
, , ,
.
,
,
. JavaScript
( )
, .
, , ,
.
x (
), .
x, .
x, JavaScript
.
x, ..
x,
, x
ReferenceError.
(..
- ) ,
.
. ,
, .

. , .
.
, ,
, , ,
, .
,
, ,
. ,


, ,
, .

with (5.7.1) (
8.6).

4
4.

JavaScript,
. , ,
.
,
, .
. , ,
, ,
, , ,
.
, .
,
,
.

.
( )
. *.
x * y x y.
,
.
JavaScript, (
), .
, , C-
, , JavaScript
.

4.1.
, ,
.

80

4.

JavaScript ,
, .
.
, :
1.23 //
"hello" //
/pattern/ //

JavaScript 3.1.
3.2.
3.2.4 10.
JavaScript,
:
true //
false //
null //
this //

true
false
null
""

true, false null 3.3 3.4.


, this
. this
- . this
, .
this 4.5, 8 (
8.2.2) 9.
, :
i // i
sum // sum
undefined // undefined - , , null

, JavaScript
, .
, undefined.
, ECMAScript 5,
ReferenceError.

4.2.
,
. -
. ,
, ,
,
. ,
.
, ,
.
.
:

4.3.

81

[] // :
//
[1+2,3+4] // 2 . 3, 7

, ,
,
:
var matrix = [[1,2,3], [4,5,6], [7,8,9]];

, ,
, .
,
.
,
. ,
, :
var sparseArray = [1,,,,5];


,
.
- -
, ,
:
var p = { x:2.3, y:-1.2 }; // 2
var q = {}; //
q.x = 2.3; q.y = -1.2; // q , p

. :
var rectangle = { upperLeft: { x: 2, y: 2 },
lowerRight: { x: 4, y: 5 } };

,
,
: JavaScript.
, ,
( , ,
,
):
var side = 1;
var square = { "upperLeft": { x: p.x, y: p.y },
'lowerRight': { x: p.x + side, y: p.y + side}};

6 7.

4.3.
,
.

82

4.

,
.
function,
( ),
, JavaScript (
) . :
//
var square = function(x) { return x * x; }

.
, function,
.
8.

4.4.

. JavaScript :
.
[ ]


, . ,
.
( ),
, .
.
:
var o = {x:1,y:{z:3}}; //
var a = [o,4,[5,6]]; //
o.x //
o.y.z //
o["x"] //
a[1] //
a[2]["1"] //
a[0].x //


,
=> 1: x o
=> 3: z o.y
=> 1: x o
=> 4: 1 a
=> 6: 1 a[2]
=> 1: x a[0]

,
. [. null undefi
ned, TypeError, JavaScript
. ( ),
(3.6).
,
, ,
.
, .
,
. ,
, undefined.

4.5.

83

. ,
, ,
, ,
, .
, ,
( ),
. ,
, ,
( 6.2.1).
6,
7.

4.5.
JavaScript ( )
. , ,
.
,
, , . :
f(0) // f - ; 0 - .
Math.max(x,y,z) // Math.max - ; x, y z - .
a.sort() // a.sort - ; .

,
,
. , ,
, TypeError. (
.
, .
8.7.7.)
,
, .
return, ,
.
undefined. ,
, ,
, 8.

.
, .
, ,
this, .
-
, ( )
,
. 9.
, ,
this .

84

4.

ECMAScript5, ,
this , undefined.
5.7.3.

4.6.
(
) .
, ,
new:
new Object()
new Point(2,3)

-
, :
new Object
new Date

JavaScript
,
{},
,
this.
. , ,
, ,
.
- ,
, .
9.

4.7.
JavaScript ,
, , ..
. 4.1,
.
4.1. JavaScript

A N

++

R 1

--

R 1

R 1

R 1

R 1

85

4.7.

A N

R 1

delete

R 1

typeof

R 1

void

R 1 undefined

*, /, %

, ,

L 2 ,

+, -

L 2 ,

L 2 ,

<<

L 2 ,

>>

L 2 ,

>>>

L 2 ,

<, <=, >, >=

L 2 ,

<, <=, >, >=

L 2 ,

instanceof

L 2 ,

in

L 2 ,

==

L 2 ,

!=

L 2 ,

===

L 2 ,

!==

L 2 ,

&

L 2 ,

L 2 ,

L 2 ,

&&

L 2 ,

||

L 2 ,

?:

R 3 , ,

R 2 ,

*=, /=, %=,


+=, -=, &=,
^=, |=, <<=,
>>=, >>>=
,

R 2 ,

, L 2 ,

,
, + =, , delete
instanceof. ,
, .
.4.1 . ,
, . ,

86

4.

, . A
( L , R
), N .
( ) ,
. , ,
, .
.

4.7.1.

. JavaScript-, *,
. ,
. . JavaScript
,
, . - -x
, x. ,, JavaScript
?:,
.

4.7.2.
,
, ,
.
.4.1 ( )
( ) .
JavaScript (
3.8) . *
, "3" * "5"
,
. 15,
"15". , JavaScript
, ,
, .
- .
+,
. , <,
,
.
.

4.7.3.
, , ,
. 4.1,
(lvalue). ,
,
. JavaScript ,

4.7.

87

. ECMAScript
,
, .

4.7.4.
, 2 * 3,
,
.
,
. :
,
,
. ++
--, . delete
: (
) undefined.
JavaScript ,

,
, .

4.7.5.
. 4.1 ,
.
, .
( )
( ).
:
w = x + y * z;

*
+, .
= ,
.
.
, :
w = (x + y)* z;

,
, , .4.1.
:
typeof my.functions[x](y)

typeof
, typeof
.

88

4.

, ,
.
:
,
.

4.7.6.
.4.1 A . L
, R
.
. ,
. ,
, :
w = x - y - z;
w = ((x - y) - z);

,
x = ~-y;
w = x = y = z;
q = a?b:c?d:e?f:g;

:
x = ~(-y);
w = (x = (y = z));
q = a?b:(c?d:(e?f:g));

, ,
.

4.7.7.

,
. JavaScript
. , w=x+y*z
w, x, y z. y z,
x ,
w. ,
,
, .
,
, .
x , z,
, x , z, .

4.8.
,
. ,

4.8.

89

, .
,

.
.
* (), / (),
% ( : ), + () - ().
, + .
,
, , ,
, . ,
, NaN. -
( ) NaN,
NaN.
/ .
,
,
. JavaScript
,
: 5/2 2.5, 2.
, 0/0
NaN; .
% .
,
. . ,
5 % 2 1, 5 % 2 1.
,
. ,
6.5 % 2.1 0,2.

4.8.1. +
+
:
1 + 2 // => 3
"hello" + " " + "there" // => "hello there"
"1" + "2" // => "12"

,
+ .
,
. +
:
, ,
, .
,
.
+ :

90

4.


, 3.8.3: Date
toString(),
valueOf(), .
valueOf(),
toString().

,
.
( NaN)
.
:
1 + 2 //
"1" + "2" //
"1" + 2 //
1 + {} //
//
true + true //
2 + null //
2 + undefined //

=> 3:
=> "12":
=> "12":
=> "1[object Object]":

=> 2:
=> 2: null 0
=> NaN: undefined NaN

, , , +
, .
, . :
1 + 2 + " blind mice"; // => "3 blind mice"
1 + (2 + " blind mice"); // => "12 blind mice"

+
, ,
.
: 2 ,
. 1 ,
.

4.8.2.

. JavaScript ,
.
, (+, -, ++ --),
. , +
- .
:
(+)
( NaN)
.
.

4.8.

91

(-)
- ,
, , .
(++)
++ (.. )
, (,
).
, 1
, .
, ++,
. (
), 1,
. (
), 1,
, .
:
var i = 1, j = ++i; // i j 2
var i = 1, j = i++; // i 2, j 1

, ++x ,
x=x+1. ++
: .
x 1, ++x 2,
x+1 11.
, -
JavaScript
. , JavaScript

.
( )
, for (
5.5.3).
(--)
-- .
, 1
. ++,
-- .
, ;
, ,
, .

.

4.8.3.

.

92

4.

,
,
.
JavaScript,
, .

,
(1= true, 0=false).
.

, 32- ,
64- .
32-
, 32-.
, 0 31.
32-
5-, .
, NaN, Infinity -Infinity 0.
(&)
&
. ,
. , 0x1234 &
0x00FF 0x0034.
(|)
|
. ,
. ,
0x1234 | 0x00FF 0x12FF.
(^)
^
. ,
, , .
,
( ) . , 0xFF00 ^ 0xF0F0
0x0FF0.
(~)
~ ,
.
. - JavaScript
~ 1.
, ~0x0f 0xFFFFFFF0, 16.
(<<)
<< ,
,
0 31. , a << 1 a
, ..

4.9.

93

, 32- .
2, 4 ..
, 7 << 2 28.
(>>)
>>
, ( 0 31). ,
, . ,
. ,
; ,
.
2 ( ),
4 .. , 7 >> 1
3, 7 >> 1 4.
(>>>)
>>> >>, ,
,
. , 1 >> 4 1, 1 >>> 4
0X0FFFFFFF.

4.9.
JavaScript.
( ,
) true false ,
.
, if, while
for (5).
,
, in instanceof.

4.9.1.
== === ,
.
true, , false, .
===, ,
, . ==,
, ,
, .
JavaScript =, == ===. ,
, .

! ,
= , ,
== , ===.
!= !== ,
== ===. != false,

94

4.

, ==, true
. 4.10, !
. , !=
!== .
3.7, JavaScript
, . ,
.
, ,
. ,
, .
=== ,
, ,
:
, .
null undefined, .
true
false, .
NaN, .
NaN ,
! , x NaN,
x !== x. NaN ,
true.
,
. 0, 0, .
16-
( 3.2) ,
. , .

, 16- .
JavaScript ,
=== == ,
. III ,
String.localeCompare().
, ,
. (
), , .
== ,
. ,
:
, ,
. , ;
, .
, ==
.
:

4.9.

95

null, undefined, .
, ,

.
- true, 1
. - false,
0 .
, ,
( 3.8.3)
.
toString(),
valueOf(). JavaScript
valueOf(), toString(), Date,
toString(). ,
JavaScript,
, .
.
:
"1" == true

true, .. -
. true 1,
. "1" 1.
, true.

4.9.2.
(
):
(<)
< true, , ;
false.
(>)
> true, ,
; false.
(<=)
<= true,
; false.
(>=)
>= true,
; false.
.
, ,
, .
:

96

4.

- ,

, 3.8.3: valueOf()
, .
, toString().

,
,
16- , .

,
. 0 0 . Infinity
, -Infinity
. - NaN,
false.
, JavaScript 16-
,
. ,
,
, .
,
ASCII
ASCII. .
, < "Zoo" "aardvark".

String.localeCompare(),
.
String.toLowerCase()
String.toUpperCase().
+ -
. + :
, .
,
:
1 + 2 //
"1" + "2" //
"1" + 2 //
11 < 3 //
"11" < "3" //
"11" < 3 //
"one" < 3 //

. : 3.
. : "12".
. 2 "2". : "12".
. : false.
. : true.
. "11" 11. : false
. "one" NaN. : false.

, , <= ( ) >= (
)
.
, .
,
NaN ( ).
false.

97

4.9.

4.9.3. in
in ,
. .
true, ,
. :
var point = { x:1, y:1 }; //
"x" in point //
"z" in point //
"toString" in point //


=> true: "x"
=> false: "z".
=> true: toString

var data = [7,8,9]; //


"0" in data //
1 in data //
3 in data //

0, 1 2
=> true: "0"
=> true:
=> false: 3

4.9.4. instanceof
instanceof , ,
. true, ,
, , .
false. 9 ,
JavaScript -.
, instanceof
-. :
var d = new Date(); //
d instanceof Date; //
d instanceof Object; //
d instanceof Number; //
var a = [1, 2, 3]; //
a instanceof Array; //
a instanceof Object; //
a instanceof RegExp; //

Date()
true; d Date()
true; Object
false; d Number

true; a
true;
false;

, Object.
, , instanceof
. instanceof
, instanceof false. ,
TypeError.
, instanceof,
, . Java
Script; 6.2.2.
o instanceof f, JavaScript f.prototype
o.
o f ( f),
true. f.prototype
o, o f instanceof
false.

98

4.

4.10.
&&, || !

.
, . ,
,
3.3.

4.10.1. (&&)
, && . ,
, &&
: true
, true.
false, false.
&& :
x == 0 && y == 0 // true , x y 0

true false,
&& true false.
, && (||),
.
&& , .
, JavaScript ,
. ( 3.3. false,
null, undefined, 0, 0, NaN "". , ,
.) &&
. ,
. ,
, . JavaScript
, ,
, , &&
true false, .
, ,
, ,
.
, &&.
.
,
, &&
.
, ,
.
, ,
,
. , ,
&& :

4.10.

99

var o = { x : 1 };
var p = null;
o && o.x // => 1: o - , o.x
p && p.x // => null: p - , p,
// p.x

, &&
. p null,
p.x TypeError.
&&, p.x , p
null undefined.
&& ,
,
&& .
, :
if (a == b) stop(); // stop() , a == b
(a == b) && stop(); //


(, , )
&&,
.
,
,
.

4.10.2. (||)
|| .
,
. , .
|| ,
, &&, .
, .
, .
, ,
.
&&, ,
,
, .
,
:
// max_width , .
// preferences. ( max_with)
// , , .
var max = max_width || preferences.max_width || 500;

100

4.

// o p p
function copy(o, p) {
p = p || {}; // p , .
//
}

4.10.3. (!)
! ,
. .
, x , !x
false. x , !x
false.
&& ||, !
( , 3) ,
. , ! true false
x ,
: !!x (3.8.2).
, !
. , p && q,
: !(p && q).
, JavaScript:
//
// p q
!(p && q) === !p || !q
!(p || q) === !p && !q

4.11.
JavaScript
=. :
i = 0 // i 0.
o.x = 1 // x o 1.

= :
, .
.
. =
, ,
.

; ,
. ,
:
(a = b) == 0

, = ==
! , = ,

4.11.

101

,
.
,

. ,
, :
i = j = k = 0; // 3 0

4.11.1.
= JavaScript
,
. , += .
:
total += sales_tax

:
total = total + sales_tax

, += , .
,
.
-=, *=, &= .
.4.2.
4.2.

+=

a += b

a = a + b

-=

a -= b

a = a b

*=

a *= b

a = a * b

/=

a /= b

a = a / b

%=

a %= b

a = a % b

<<=

a <<= b

a = a << b

>>=

a >>= b

a = a >> b

>>>=

a >>>= b

a = a >>> b

&=

a &= b

a = a & b

|=

a |= b

a = a | b

^=

a ^= b

a = a ^ b

:
a op= b

op , :
a = a op b

102

4.

a . .
, a ,
,
. , :
data[i++] *= 2;
data[i++] = data[i++] * 2;

4.12.
, JavaScript
JavaScript,
, . JavaScript
eval():
eval("3+2") // => 5


, .
eval(),
.
eval()
,
.

eval() ?
eval() , ,
,
. eval()
,
,
. JavaScript
.
eval() , ,
, . ,
eval(), .
eval() ,
:
var f = eval;
var g = f;

,
, g().
, eval (
). ,
eval(), ,
( 4.12.2 4.12.3).

4.12.

103

4.12.1. eval()
eval() . ,
, . ,

JavaScript SyntaxError .

undefined,
.
, eval() .
eval() ( )
, ,
.
, .
x eval("x"),
. eval("x=1")
. eval("var y = 3;"),
y.
:
eval("function f() { return x+1; }");

eval() , ,
, .
, , eval(),
,
.
, eval("return;"), return
, ,
, ,
.
( , x=0),
eval(). eval()
SyntaxError.

4.12.2. eval()
eval()
JavaScript.
,
eval(). JavaScript,
eval() ?
JavaScript,
ECMAScript3 ,
. eval() ,
eval, EvalError.
.
eval()
.

104

4.

,
,
.
ECMAScript5 EvalError
eval(), -.
eval() eval (
). eval()
.
,
.
:
var geval = eval; // eval
var x = "global", y = "global"; //
function f() { //
var x = "local"; //
eval("x += 'changed';"); //
return x; //
}
function g() { //
var y = "local"; //
geval("y += 'changed';"); //
return y; //
}
console.log(f(), x); //
console.log(g(), y); //

eval

eval

eval

eval .

: "localchanged global":
: "local globalchanged":

, eval()

. :
,
. ,

. , , ,
eval() , .
IE9 Internet Explorer :
eval(), ,
. (
EvalError: .) IE
execScript(),
, ,
. (, eval(), execScript()
null.)

4.12.3. eval()
(5.7.3), ECMAScript5,
eval()
eval. eval() ,
, , ,

4.13.

105

use strict, eval()


. ,
,
.
, eval() ,
eval .
eval() .
, , catch eval.

4.13.
JavaScript ,
.

4.13.1. (?:)
( )
JavaScript, .
?:, -.
, ?, ? :,
:. :
x > 0 ? x : -x // x

.
.
,
. ,
.
- , , .
if, ?:
. ,
, ( ),
, , , :
greeting = "hello " + (username ? username : "there");

if, :
greeting = "hello ";
if (username)
greeting += username;
else
greeting += "there";

4.13.2. typeof
typeof ,
. ,
. typeof
, JavaScript:

106

4.

typeof x

undefined

"undefined"

null

"object"

true false

"boolean"

NaN

"number"

"string"

"function"

"object"

, ,
"undefined", "boolean", "number" "string".

typeof , , :
(typeof value == "string") ? "'" + value + "'" : value

typeof switch ( 5.4.3).


, typeof ,
typeof ,
:
typeof(i)

, null typeof
object. null ,
. , ,
typeof , object.
JavaScript object.
typeof
object,
.
, ,
instanceof (4.9.4), class (6.8.2)
constructor ( 6.8.1 9.2.2).
JavaScript
, typeof ,
. JavaScript
. ,
,
. ECMAScript3 ,
typeof function
, . ECMAScript5
, typeof function
,
.
-
JavaScript. Microsoft
,
IE9 typeof object ,

4.13.

107

. IE9
- .
8.7.7.

4.13.3. delete
delete
, .1 ,
, delete
, , .
:
var o = {x: 1, y: 2}; //
delete o.x; //
"x" in o // => false:
var a = [1,2,3]; //
delete a[2]; //
2 in a // => false:
a.length // => 3: ,

:
undefined. .
undefined,
in
(4.9.3).
. .
delete , .
,
true. delete
.
delete true.
:
JavaScript .
,
var. , ,
function, .
, ECMAScript5, delete
SyntaxError,
, ,
: ,
(4.4). ,
, delete TypeError,
(6.7).
, delete false,
, .
1

C++ , delete JavaScript


delete C++. JavaScript
, .
delete C++, , .

108

4.

delete:
var o = {x:1, y:2}; //
delete o.x; //
typeof o.x; //
delete o.x; //
delete o; //
//
delete 1; //
this.x = 1; //
delete x; //
//
x; //

;
; true
; "undefined"
; true
; false
.
; true
var
: true ;
. 'delete this.x' .
: x

delete 6.3.

4.13.4. void
void
. :
, undefined.
, void
, .
JavaScript, URL
JavaScript:,
, . , void
HTML- <a>:
<a href="javascript:void window.open();"> </a>

HTML , URL javascript:


onclick, void
.

4.13.5. (,)
(,)
. ,
. :
i=0, j=1, k=2;

2 :
i = 0; j = 1; k = 2;

, ,

.
for (5.5.3) :
// var
// : 2 (i++ j--)
// ( for), 1 .
for(var i=0,j=10; i < j; i++,j--)
console.log(i+j);

5
5.

4 JavaScript.
JavaScript, .

, JavaScript (2.5).
, ,
- .
- , ,
. ,
,
-.
-,
.
JavaScript
. JavaScript
.
, - , ,
, JavaScript
, ,
:
, if switch,
JavaScript
.
, while for,
.
, break, return throw,
.
, , Ja
vaScript .
.5.1, . JavaScript

110

5.

, , ,
JavaScript, .

5.1. -
JavaScript ,
. ( 5.7.3, -,
.)
4. -
. :
greeting = "Hello " + name;
i *= 3;

, ++ --
. ,
:
counter++;

delete .
,
:
delete o.x;

-.
:
alert(greeting);
window.close();

,
, -,
. -
, ,
. ,
:
Math.cos(x);

,
:
cx = Math.cos(x);

,
.

5.2.
( 4.13.5),
,
.

5.2.

111

, . ,

, JavaScript :
{
x = Math.PI;
cx = Math.cos(x);
console.log("cos() = " + cx);
}

, . -
, .
, . ,
, . ,
. ,
, JavaScript ,
, ,
( 3.10.1).

JavaScript .
, JavaScript
. JavaScript
. , while
, .
,
.
,
JavaScript .
:
, . :
;

, JavaScript
. ,
. for ( for
5.5.3):
// a
for(i = 0; i < a.length; a[i++] = 0) ;

a[i++] = 0,
. JavaScript , ,
.
,
for, while if
, . ,
, :
if ((a == 0) || (b == 0)); // ! ...
o = null; // .

112

5.

,
, . :
for(i = 0; i < a.length; a[i++] = 0) /* */ ;

5.3. -
var function -
, , .
( ),
, .
- , ,
,
.
, , var function,
.
3.9 3.10,
8.

5.3.1. var
var .
:
var _1 [ = _1] [ ,..., _n [= _n]]

var
; -
, . :
var i; //
var j = 0; //
var p, q; //
var greeting = "hello" + name; //
var x = 2.34, y = Math.cos(0.75), r, theta; //
var x = 2, y = x*x; //
var x = 2, //
f = function(x) { return x*x }, //
y = f(x); //


,




...

var ,
, .
var
, . 3.10.2,
. ,
, ,
var, .
var ,
, (unde
fined). 3.10.1,
, ,

5.3. -

113

.
, var,
undefined.
, var
for for/in. (
, .)
3.9:
for(var i = 0; i < 10; i++) console.log(i);
for(var i = 0, j=10; i < 10; i++,j--) console.log(i*j);
for(var i in o) console.log(i);

,
.

5.3.2. function
function JavaScript
. 4.3 .
.
:
var f = function(x) { return x+1; } //
function f(x) { return x+1; } //

:
function _([1 [,2 [..., n]]]) {

}

_ ,
.
, .
, .
JavaScript-,
.
.
. ,
function. while
, ,
.
:
function hypotenuse(x, y) {
return Math.sqrt(x*x + y*y); // return
}
function factorial(n) { //
if (n <= 1) return 1;
return n * factorial(n - 1);
}

JavaScript-
,

114

5.

, ..
if, while . -
, , ECMAScript
.
JavaScript ,
- ,
.
,
. ,
,
. ,
var, , functi
on, ,
.
var ,
, .
function , :
, , ,
. ,
, .
var, ,
.
.

5.4.

.
,
. , ,
JavaScript , ,
,
, ,
.
Java
Script if/else, switch,
.

5.4.1. if
if ,
JavaScript , ,
. . :
if ()

.
, .

5.4.

115

, . (
3.3.) :
if (username == null) // username null undefined,
username = "John Doe"; //

:
// username null, undefined, 0, "" NaN,
// .
if (!username) username = "John Doe";

,
if.
JavaScript
if ,
. if
:
if (!address) {
address = "";
message = ", .";
}

if else,
, . :
if ()
1
else
2

1,
, 2, . :
if (n == 1)
console.log(" 1 .");
else
console.log(" " + n + " .");

if else
, else
if. :
i = j = 1;
k = 2;
if (i == j)
if (j == k)
console.log("i k");
else
console.log("i j"); // !!

if ,
if. , (
, ), if else.
,
JavaScript :

116

5.

if (i == j) {
if (j == k)
console.log("i k");
else
console.log("i j"); // !
}

JavaScript (
), else if.
,
, , :
if (i == j) {
if (j == k) {
console.log("i k");
}
}
else { // - !
console.log("i j");
}

,
if else (
, while) ,
.
, .

5.4.2. else if
if/else
, .
?
else if.
JavaScript; ,
if/else:
if (n == 1) {
// 1
}
else if (n == 2) {
// 2
}
else if (n == 3) {
// 3
}
else {
// else , 4
}

.
if, if else
. else if
,
:

5.4.

117

if (n == 1) {
// 1
}
else {
if (n == 2) {
// 2
}
else {
if (n == 3) {
// 3
}
else {
// else
// , 4
}
}
}

5.4.3. switch
if ,

else if. ,
.
if.
switch .
switch :
switch() {

}

switch , .
case,
. case
, ,
. switch,
, case, (
===). ,
, , case.
case ,
, default:.
default: , switch .
switch ,
. switch
if/else, :
switch(n) {
case 1: // , n === 1
// 1.
break; //
case 2: // , n === 2

118

5.

// 2.
break; //
case 3: // , n === 3
// 3.
break; //
default: // ...
// 4.
break; //
}

break case.
break, ,
switch ,
. case switch
, .
break switch
case, ,
, .
, case
, 99% case
break. ( switch break
return.
switch case.)
switch;
, :
function convert(x) {
switch(typeof x) {
case 'number': //
return x.toString(16);
case 'string': // ,
return '"' + x + '"';
default: //
return x.toString()
}
}

,
case . switch
, ECMAScript
case .
switch switch,
case , ,
.1

, case
, switch JavaScript (
) switch C, C++ Java. case
, , .
, switch
.

5.5.

119

===, ==,
- .
switch
case, case,
, .
case .
, case
switch, switch
default:. default: , switch
. , default:
switch case.
,
switch.

5.5.
,
, JavaScript.
,
,
. JavaScript
: while, do/while, for for/in.
.
.
7.6, Array.

5.5.1. while
if JavaScript,
JavaScript while.
:
while ()

while .
, ,
, .
, , ,
.
, ,
(while) . ,
while(true).
, JavaScript
.
.
, , ,
. , ( )
,

120

5.

. , .. ,
, !
while, 0 9:
var count = 0;
while (count < 10) {
console.log(count);
count++;
}

, count 0,
, .
10 , false (.. count
10), while
. -
, count.
i, j k,
, .

5.5.2. do/while
do/while while, ,
, . ,
.
:
do

while ();

do/while , while. ,
, ,
, .
do/while:
function printArray(a) {
var len = a.length, i = 0;
if (len == 0)
console.log(" ");
else {
do {
console.log(a[i]);
} while (++i < len);
}
}

do/while while . -
, do do ( ),
while ( ). -
, while, do . while
,
.

5.5.

121

5.5.3. for
for ,
, while. for
, , .
-.
. ,
- -
,
. , ,
. for
:
for(; ; )

, (
), ,
.
, for,
.
for, while:1
;
while() {

;
}

,
. , ,
( ). JavaScript ,
var,
.
,
. ,
, .
. ,
.
, , ++ --.
0 9 for, .
while, :
for(var count = 0; count < 10; count++)
console.log(count);

, ,
,
. JavaScript,
1

, continue 5.6.3,
while for.

122

5.


,
for:
var i, j
for(i = 0, j = 10; i < 10; i++, j--)
sum += i * j;

, ,
. ,
. for
(,
, next):
function tail(o) { // o
for(; o.next; o = o.next) /* */ ; // , o.next
return o; //
}

.
for ,
. ,
, for(;;)
, while(true).

5.5.4. for/in
for/in for,
for. for/in :
for ( in )

,
,
(4.7.3), var,
, , .
, . ,
, .
for:
for(var i = 0; i < a.length; i++) // i
console.log(a[i]); //

for/in .
for(var p in o) // o p
console.log(o[p]); //

for/in, JavaScript
. null undfefined,
.1
1

, ECMAScript3,
TypeError.

5.5.

123

, -
(3.6). .

.
( ).
, for/in
, ,
. , ..
. ,
, :
var o = {x:1, y:2, z:3};
var a = []; var i = 0;
for(a[i++] in o) /* */;

JavaScript ,
, for/in.
, 0, 1 2 ,
:
for(i in a) console.log(i);

for/in
, (6.7).
, JavaScript,
. , toString(), for/in
toString.
.
, , . (
, ECMAScript5,
, , 6.7.)
, ( 6.2.2),
for/in.
for/in , ,
. ,
. (
, .)

5.5.4.1.
ECMAScript , for/in
. JavaScript
,
,
. ,
, .
, ,
, .
.
, :

124

5.

;
, ;
delete


Object.defineProperty() (6.7)

.
( ) (6.2.2)
, ,
.
(6.1.3) ,
, -

. ( )
, ,

,
(.. ).

5.6.
JavaScript
. , Java
Script . break
.
continue ,
.
JavaScript ,
break continue ,
.
return
. throw
try/catch/
finally, .
:

, ,
.
.

5.6.1.

:
:

, ,
.

5.6.

125

, ,
, . ,
break continue,
, . break
continue JavaScript,

. while continue,
:
mainloop: while(token != null) {
// ...
continue mainloop; //
// ...
}

, ,
JavaScript, .
,
,
. ,
(, , ).
,
,
. .
.

5.6.2. break
break
switch. :
break;

break switch,
break .
break
switch.
, - .
,
break,
.
.
break,
:
for(var i = 0; i < a.length; i++) {
if (a[i] == target) break;
}

JavaScript break
( ):
break _;

126

5.

break ,
.

break .
switch: break
.
,
.
break
. , JavaScript
:
break ,
, ,
(2.5).
break ,
,
switch. :
var matrix = getData(); // 2- -
// .
var sum = 0, success = false;
// ,
compute_sum: if (matrix) {
for(var x = 0; x < matrix.length; x++) {
var row = matrix[x];
if (!row) break compute_sum;
for(var y = 0; y < row.length; y++) {
var cell = row[y];
if (isNaN(cell)) break compute_sum;
sum += cell;
}
}
success = true;
}
// break .
// success == false, , - .
// sum .

, , break, ,
. ,
.

5.6.3. continue
continue break.
continue .
continue , break:
continue;

continue :
continue _;

5.6.

127

continue, , ,
.
.
continue,
. :
while
,
true, .
do/while ,
.
for

, , .
for/in
.
continue while
for: while , for
, .
for for
while. continue
-, for while
.
continue
:
for(i = 0; i < data.length; i++) {
if (!data[i]) continue; //
total += data[i];
}

continue, break,
, ,
, continue. ,
break, continue
.

5.6.4. return
,
. return
, . return
:
return ;

return .
.
return,
. :
function square(x) { return x*x; } // return
square(2) // 4

128

5.

return,
,
, .
undefined. return
, :
,
return, .
return ,
undefined
. :
function display_object(o) {
// , null undefined
if (!o) return;
// ...
}

- JavaScript
, return
.

5.6.5. throw
, -
. (throw)
.
(catch) , .. ,
. JavaScript
,
throw.
try/catch/finally,
.
throw :
throw ;

. throw
, , ,
. JavaScript ,
Error ,
. Error name, ,
message, , - (
Error ).
, Error :
function factorial(x) {
// , !
if (x < 0) throw new Error("x ");
//
for(var f = 1; x > 1; f *= x, x--) /* */ ;
return f;
}

5.6.

129

, JavaScript
1
. catch
try/catch/finally, .
, ,
catch,
, .
, .
, try/catch/finally,
, ,
, .
JavaScript .
,
.

5.6.6. try/catch/finally
try/catch/finally Java
Script. try ,
. try catch
, , - try .
catch finally, ,
,
, try. catch, finally
, try
. try, catch finally
. ,
, .
try/
catch/finally:
try {
// .
// -
// throw, // , .
}
catch (e) {
// , try
// . e,
// Error , throw.
// ,
// , - ,
// throw.
}
finally {
// , , ,
// try. , try :
1

.
. . .

130

5.

// 1) ,
// 2) - break, continue return
// 3) , catch
// 4) ,
//
}

, catch
. .
, (,
Error). ,
catch, catch.
try/catch.
factorial(), ,
prompt() alert() JavaScript :
try {
//
var n = Number(prompt(" ", ""));
// , ,
var f = factorial(n);
//
alert(n + "! = " + f);
}
catch (ex) { // ,
alert(ex); //
}

try/catch finally. finally


, catch,
. . finally
, - try,
,
try.
try.
try,
finally, .
try return,
continue break,
finally.
try catch
, catch,
finally. catch,
finally, catch,
.
finally return, conti
nue, break throw , ,
.
, finally ,
. finally

5.7.

131

return, ,
, .
try finally catch.
finally ,
,
try break, continue return. , -
continue
while, for.
try/finally, while,
, for, continue:
// for( ; ; ) ;
;
while( ) {
try { ; }
finally { ; }
}

, while, break,
(-
), for,
finally, for while.

5.7.
JavaScript with,
debugger use strict.

5.7.1. with
3.10.3
,
. with
. :
with ()

,
, .
with (5.7.3)
:
. JavaScript,
with,
, with.
with
. JavaScript
, , HTML-:
document.forms[0].address.value

132

5.

,
with,
:
with(document.forms[0]) {
// , :
name.value = "";
address.value = "";
email.value = "";
}


document.forms[0] .

, JavaScript ,
address. with ,
, :
var f = document.forms[0];
f.name.value = "";
f.address.value = "";
f.email.value = "";

,
.
:
with(o) x = 1;

o x, 1
. x o,
, x = 1 with.
x
. with
o,
.

5.7.2. debugger
debugger .
-, JavaScript ( )
.
: JavaScript
, ,
.. , ,
f() ,
, ,
. ,
f(), , :
function f(o) {
if (o === undefined) debugger; //
... // .
}

5.7.

133

, f() ,
, ,
, .
debugger ECMA
Script 5,
. , : debugger
. , ,
. , ,
Firebug Firefox,
-, ,
debugger .

5.7.3. "use strict"


"use strict" , ECMAScript5.
( , "use
strict" ). "use strict"
:
:
, (
). JavaScript,
ECMAScript5,
.
ECMAScript, , use
, .
,
.
: "use strict"
-
, JavaScript
, .
,
,
.
"use strict" , ,
( )
. ( ),
"use strict".
,
"use strict". ,
eval(), eval()
"use strict".
.
ECMAScript 5, ,
,

. (
):

134

5.

with.
:

,
, , , catch
, ReferenceError. (

.)
, (
), this undefined. (
, , this
.) , ,
:
var hasStrictMode = (function() { "use strict"; return this===undefined}());

, call()
apply(), this ,
call() apply(). (
null undefined ,
.)
,
,
TypeError. ( .)
, eval(),

, .
,
eval(). , eval()
.
arguments (8.3.2)
, .
arguments arguments
.
SyntaxError, delete
, ,
. (
delete false.)

TypeError. (
delete false.)

. (
.)

. (
.)

135

5.8. JavaScript-

( 0, x). (

.)
eval arguments
, .
, ,
,
catch.
.
arguments.caller arguments.callee
TypeError. caller
arguments Type
Error. ( .)

5.8. JavaScript-
JavaScript. .5.1

.
5.1. JavaScript

break

break [_];


, switch
_

case

case :


switch

continue

continue [_];


,
_

debugger

debugger;

default

default:

,
switch

do/while

do while ();

while

for

for (; ; )

for/in

for ( in )

function

function _([[,...]])
{

}

136

5.
5.1 ()

if/else

if () 1
[else 2]

1
2

return

return [];

switch

switch () { }


case default

throw

throw ;

try

try{ }
[catch{ }]
[finally { . }]

use strict

"use strict"

var

var [ = ] [ ,... ];

while

while ()

with

with ()


. (
.)

6
6.

JavaScript.
: (
)
. ,
. ,
, .
-: ,
, ,
. ,
. JavaScript
,
. ,
Java
Script.
JavaScript

,
. ,
( , )
.
JavaScript, , , true, false,
null undefined, . ,
, ,
(3.6).
, 3.7 ,
, .
x , var y = x;,
y , .
, y,
x.

138

6.

,
, , , .
.
,
ECMAScript5.
. ,
,
. ,
JavaScript, (ECMAScript5) ( ).
6.6.

, :
writable .
enumerable
for/in.
configurable , ..
.
ECMAScript5 ,
, , . ECMAScript5
.
, 6.7.
:
prototype ,
.
class
.
extensible ( ECMAScript 5)
.

6.1.3 6.2.2,
6.8.
, ,
JavaScript :
,
ECMAScript. , ,
() .
, (
-), JavaScript. HTMLEle
ment, - JavaScript,
.
, ,
, Function
JavaScript.
,
JavaScript.

139

6.1.

.
, .

6.1.
, new
(ECMAScript5) Object.create().
.

6.1.1.

.
( /), .
(
). , Java
Script, ( )
. :
var empty = {}; //
var point = { x:0, y:0 }; //
var point2 = { x:point.x, y:point.y+1 }; //
var book = {
"main title": "JavaScript", //
'sub-title': "The Definitive Guide", //
//
"for": "all audiences", //
//
author: { //
firstname: "David", //
surname: "Flanagan" //
}
};





,

for - ,


. ,
.

ECMAScript5 ( ECMAScript3)
.
, , ECMA
Script 3 . ECMAScript 5 ,
, .
ECMAScript3 ,
IE .
,
, .
, .
,
, ,
,
.

140

6.

6.1.2. new
new .
. , ,
.
JavaScript
. :
var o = new Object(); // : , {}.
var a = new Array(); // : , [].
var d = new Date(); // Date,
var r = new RegExp("js"); // RegExp
// .


-
. , , 9.

6.1.3.
,
, . JavaScript
( null, ), .
,
.
, ,
-, JavaScript : Object.pro
totype. , new
, prototype -
. , new Object(),
Object.prototype,
{}. ,
new Array(), Array.prototype, ,
new Date(), Date.prototype.
Object.prototype , :
. -
, .
( )
Object.prototype. , Date.prototype Object.proto
type, Date, new Date(),
, Date.prototype Object.prototype.
- .
6.2.2.
, 6.8.1. 9
:
,
- -
prototype ,
.

6.1.

141

6.1.4. Object.create()
ECMAScript5 Object.create(),
.
Object.create()
, .
6.7.
Object.create() , ,
. ,
-:
var o1 = Object.create({x:1, y:2}); // o1 x y.

, , null,
- ,
, toString() ( ,
+):
var o2 = Object.create(null); // o2 , .

(,
, {} new Object()),
Object.prototype:
var o3 = Object.create(Object.prototype); // o3 ,
// {} new Object().

(
: )
, ECMAScript3
, 6.1.1
6.1. ,
// inherit() ,
// - p. Object.create() ECMAScript5,
// , .
function inherit(p) {
if (p == null) throw TypeError(); // p null
if (Object.create) // Object.create() ...
return Object.create(p); // .
var t = typeof p; //
if (t !== "object" && t !== "function") throw TypeError();
function f() {}; // .
f.prototype = p; // prototype
// p.
return new f(); // f()
// "" p.
}

(Douglas Crockford) , ,
. . http://javascript.crockford.com/prototypal.html.

142

6.

inherit() ,
9. ,
, . ,
inherit() Object.create():

, Object.create().
inherit() 9.
inherit() ,
( ) ,
.
, .
, .
,
:
var o = { x: " " };
library_function(inherit(o)); // o

, ,
JavaScript.
.

6.2.
(.)
([]), 4.4.
, .
, .

, , :
var author = book.author; // "author" book.
var name = author.surname // "surname" author.
var title = book["main title"] // "main title" book.

,
,
,
:
book.edition = 6; // "edition" book.
book["main title"] = "ECMAScript"; // "main title".

ECMAScript3 , ,
: o.for o.class,
for , class ,
. ,
,
: o["for"] o["class"]. ECMA
Script5 (
ECMAScript3)
.

6.2.

143

,
.
, ,
. 7, ,
.

6.2.1.
,
:
object.property
object["property"]

, ,
C
Java. , ,
, ,
, .
( ). JavaScript
, , .
C, C++, Java
,
. JavaScript
, :
.
(.)
.
,
.
,
([]), .
JavaScript ,
. , , Java
Script :
var addr = "";
for(i = 0; i < 4; i++)
addr += customer["address" + i] + '\n';

address0,
address1, address2 address3 customer.


. ,
,
. , ,
,
.
,
, .

144

6.

portfolio.
.
,
. , , 50 IBM,
portfolio.ibm 50.
, ,
:
function addstock(portfolio, stockname, shares) {
portfolio[stockname] = shares;
}

,
.
,
(.) portfolio.
[],
(
) (
).
5 for/in ( ,
6.5). JavaScript
, .
,
portfolio:
function getvalue(portfolio) {
var total = 0.0;
for(stock in portfolio) { //
var shares = portfolio[stock]; //
var price = getquote(stock); //
total += shares * price; //
}
return total; //
}

portfolio:



.

6.2.2.
JavaScript
-.
, .

inherit() 6.1.
, x o. o
,
x o. -
, ,
. ,
x , .
, prototype ,
, .

6.2.
var
o.x
var
p.y
var
q.z
var
q.x

o
=
p
=
q
=
s
+

= {} //
1; //
= inherit(o); //
2; //
= inherit(p); //
3; //
= q.toString(); //
q.y //

145

o Object.prototype
x.
p o Object.prototype
y.
q p, o Object.prototype
z.
toString Object.prototype
=> 3: x y o p

, x
o. o ( )
x,
. o x.
o x,
.

, . ,
o x, ,
. ( , ,
6.2.3.) ,

. , ,
,
JavaScript,
:
var unitcircle = { r:1 }; //
var c = inherit(unitcircle); //
c.x = 1; c.y = 1; //
c.r = 2; //
unitcircle.r; //

,
c r
c
c
=> 1: -

,
/
. o x
(6.6),
x o
. ,
o, , , ,
- ,
o, .

6.2.3.

. ,
.
.
x
o, o.x undefined. ,

146

6.

book sub-title,
subtitle:
book.subtitle; // => undefined:


. null undefined ,
. , :
// TypeError. undefined length
var len = book.subtitle.length;

, book book.subtitle (
), book.subtitle.length,
.
:
//
var len = undefined;
if (book) {
if (book.subtitle) len = book.subtitle.length;
}
// JavaScript
// subtitle
var len = book && book.subtitle && book.subtitle.length;

,
TypeError, ,
&&, 4.10.1. ,
null undefined
TypeError.

:
. ,
. , ,
, :
// prototype .
Object.prototype = 0; // ;
// Object.prototype

JavaScript
, ECMAScript 5.
TypeError.
, ,
, , ,
. p
o :
o p, :
, . (, ,
defineProperty(), ,
,
.)

147

6.3.

o p, :

, ,
.
o p; o p
extensible (6.8.3) o
false. p o
, p
o. o ,
.

6.3.
delete ( 4.13.3) .
.
, delete
:
delete book.author; // book author.
delete book["main title"]; // "main title".

delete
. ( ,
-, . ,
.)
delete true
(,
). delete
true, ,
:
o = {x:1}; //
delete o.x; //
delete o.x; //
delete o.toString; //
delete 1; //

o x toString
x true
(x ) true
(toString ) true
, true

delete , configurable
false. (
.)
, ,
.
TypeError. (
ECMAScript 3) delete
false:
delete Object.prototype; //
var x = 1; //
delete this.x; //
function f() {} //
delete this.f; //

148

6.



delete :
this.x = 1; // ( var)
delete x; //

delete SyntaxError,
, x,
:
delete x; // SyntaxError
delete this.x; //

6.4.
JavaScript ,

.
in, hasOwnProperty()
propertyIsEnumerable() .
in ,
( ) . true,
:
var o = { x: 1 }
"x" in o; // true: o "x"
"y" in o; // false: o "y"
"toString" in o; // true: o toString

hasOwnProperty() ,
. false:
var o = { x: 1 }
o.hasOwnProperty("x"); // true: o x
o.hasOwnProperty("y"); // false: y
o.hasOwnProperty("toString"); // false: toString -

propertyIsEnumerable()
hasOwnProperty(). true,
, enumerable true.
. ,
JavaScript, ,
ECMAScript5, ,
.
var o = inherit({ y: 2 });
o.x = 1;
o.propertyIsEnumerable("x"); // true: o . x
o.propertyIsEnumerable("y"); // false: y - , .
Object.prototype.propertyIsEnumerable("toString"); // false:

in
!==
undefined:

149

6.5.
var o = { x: 1 }
o.x !== undefined; // true: o x
o.y !== undefined; // false: o y
o.toString !== undefined; // true: o toString

in ,
. in
, undefined.
:
var o = { x: undefined } //
o.x !== undefined //
o.y !== undefined //
"x" in o //
"y" in o //
delete o.x; //
"x" in o //

undefined
false: , undefined
false:
true:
false:
x
false:

, !==, !=.
!== === undefined null,
:
// o x, null undefined,
// .
if (o.x != null) o.x *= 2;
//
//
//
if

o x, false,
. x undefined, null, false, "", 0 NaN,
.
(o.x) o.x *= 2;

6.5.

.
for/in, ECMAScript5
.
for/in 5.5.4.
( )
, .
, , , ,
, (
, ,
). :
var o = {x:1, y:2, z:3}; //
o.propertyIsEnumerable("toString") //
for(p in o) //
console.log(p); //


=> false:

x, y z, toString

( )
Object.prototype,
. ECMAScript5

150

6.

,
for/in. ,
, for/in.
:
for(p in o) {
if (!o.hasOwnProperty(p)) continue; //
}
for(p in o) {
if (typeof o[p] === "function") continue; //
}

6.2 , for/
in . extend(), ,
JavaScript.1
6.2. ,

/*
* p o o.
* o p ,
* o p.
* .
*/
function extend(o, p) {
for(prop in p) { // p.
o[prop] = p[prop]; // o.
}
return o;
}
/*
* p o o.
* o p ,
* o .
* .
*/
function merge(o, p) {
for(prop in p) { // p.
if (o.hasOwnProperty[prop]) continue; // o.
o[prop] = p[prop]; // o.
}
return o;
}
/*
* o , p.
* o.
*/

extend(), , ,
Internet Explorer.
extend() 8.3.

6.5.

151

function restrict(o, p) {
for(prop in o) { // o
if (!(prop in p)) delete o[prop]; // , p
}
return o;
}
/*
* o , p. o.
*/
function subtract(o, p) {
for(prop in p) { // p
delete o[prop]; // o (
// )
}
return o;
}
/*
* , ,
* , o p. , o p,
* , p.
*/
function union(o,p) { return extend(extend({},o), p); }
/*
* , ,
* , o p. - o p,
* p
*/
function intersection(o,p) { return restrict(extend({}, o), p); }
/*
* o.
*/
function keys(o) {
if (typeof o !== "object") throw TypeError(); // .
var result = []; //
for(var prop in o) { //
if (o.hasOwnProperty(prop)) // ,
result.push(prop); // array.
}
return result; // .
}

for/in ECMAScript5 ,
. , Object.keys(),
.
keys() 6.2.
ECMAScript 5, , Object.
getOwnPropertyNames(). Object.keys(),
,
. ECMAScript3
, ECMAScript3
.

152

6.

6.6.
, ,
. ECMAScript 51 ,
(getter) (setter). ,
,
, ,
.
,
( ).
.
,
, ,
. . ,
, .
,
writable. , ,
/. ,
. ,
( )
undefined.

:
var o = {
//
data_prop: value,
//
get accessor_prop() { /* */ },
set accessor_prop(value) { /* */ }
};

,
function get
/ set. ,
, , ,
.
,
. X Y
, ,
:
var p = {
// x y - , /.
x: 1.0,

ECMAScript 3 ,
IE.

6.6.

153

y: 1.0,
// r - / .
// .
get r() { return Math.sqrt(this.x*this.x + this.y*this.y); },
set r(newvalue) {
var oldvalue = Math.sqrt(this.x*this.x + this.y*this.y);
var ratio = newvalue/oldvalue;
this.x *= ratio;
this.y *= ratio;
},
// theta - .
get theta() { return Math.atan2(this.y, this.x); }
};

this
. , ,
, .. this
. r x
y, this.x this.y. this
8.2.2.
,
, p, ,
.
x y, r theta:
var q = inherit(p); //
q.x = 1; q.y = 1; //
console.log(q.r); //
console.log(q.theta); //

,
q

API,

( ).

:
//
var serialnum = {
// .
// $ , .
$n: 0,
//
get next() { return this.$n++; },
// n,
set next(n) {
if (n >= this.$n) this.$n = n;
else throw " ";
}
};

,
.

154

6.

// ,
// . , "random.octet"
// 0 255.
var random = {
get octet() { return Math.floor(Math.random()*256); },
get uint16() { return Math.floor(Math.random()*65536); },
get int16() { return Math.floor(Math.random()*65536)-32768; }
};

,
.
, .

6.7.
,
, . ECMAScript 3
: ,
, ECMAScript3,
, ,
. (API),
ECMAScript 5
. API ,
:
- ,
;
,
.

. ,
, .
, .
: (value), (writable),
(enumerable)
(configurable).
value writable:
.
: (get), (set),
(enumerable) (configurable).
,
ECMAScript5, ,
(property descriptor), .
,
, . -
value, writable, enumerable configurable.
value writable
get set. writable, enumerable configurable
, get set .

6.7.

155

Object.get
OwnPropertyDescriptor():
// {value: 1, writable:true, enumerable:true, configurable:true}
Object.getOwnPropertyDescriptor({x:1}, "x");
// octet random, .
// { get: /*func*/, set:undefined, enumerable:true, configurable:true}
Object.getOwnPropertyDescriptor(random, "octet");
// undefined .
Object.getOwnPropertyDescriptor({}, "x"); // undefined,
Object.getOwnPropertyDescriptor({}, "toString"); // undefined,

, Object.getOwnPropertyDescriptor()
.
, (
Object.getPrototypeOf() 6.8.1).

, Object.defineProperty(),
, ,
:
var o = {}; //
// x 1.
Object.defineProperty(o, "x", { value : 1,
writable: true,
enumerable: false,
configurable: true});
// ,
o.x; // => 1
Object.keys(o) // => []
// x
Object.defineProperty(o, "x", { writable: false });
//
o.x = 2; // , TypeError
o.x // => 1
// , :
Object.defineProperty(o, "x", { value: 2 });
o.x // => 2
//
Object.defineProperty(o, "x", { get: function() { return 0; } });
o.x // => 0

, Object.defineProperty(),
.
false undefined.

. ,

.

156

6.

,
Object.define Properties().
, .
,
. :
var p = Object.defineProperties({}, {
x: { value: 1, writable: true, enumerable:true, configurable:true },
y: { value: 1, writable: true, enumerable:true, configurable:true },
r: {
get: function() { return Math.sqrt(this.x*this.x + this.y*this.y) },
enumerable:true,
configurable:true
}
});

,
,
. , Object.defineProperties()
( Object.defineProperty()).
Object.create(), ECMAScript5,
6.1, ,
, .
, ,
Object.defineProperties(). Object.create()
,
.
Object.defineProperty() Object.defineProperties()
TypeError, . ,
(6.8.3).
, TypeError,
. writable
value. configurable
( ).
. , ,
, , . ,
, , ,
.
. Object.defineProperty() Object.defineProperties(),
, TypeError:
,
, .
, con
figurable enumerable.
,

.
,
.

6.7.

157

writable false true, true false.


,

. ,
, (
,
).
6.2 extend(),
.
. ,
,
. 6.3 extend(),
Object.getOwnPropertyDescriptor() Object.defineProperty().
,
Object.prototype , .
6.3.
/*
* extend() Object.prototype.
* ,
* . ,
* .
* ( ),
* , .
*/
Object.defineProperty(Object.prototype,
"extend", // Object.prototype.extend
{
writable: true,
enumerable: false, //
configurable: true,
value: function(o) { //
// ,
var names = Object.getOwnPropertyNames(o);
//
for(var i = 0; i < names.length; i++) {
// ,
if (names[i] in this) continue;
// o
var desc = Object.getOwnPropertyDescriptor(o,names[i]);
//
Object.defineProperty(this, names[i], desc);
}
}
});

6.7.1.

,
6.6, ,

158

6.


. ECMAScript5
Object.getOwnPropertyDescriptor() Object.defineProperty().
JavaScript ( - IE)
get set
ECMAScript5. , API
. API
, . __lookupGetter__() __lookupSetter__()
. __define
Getter__() __defineSetter__() :
,
.
, , .
.

6.8.
prototype, class extensible.
; ,
( ).

6.8.1. prototype
prototype , .
(
6.1.3 6.2.2.) ,
o,
prototype o. , ,
prototype, ,
prototype.
prototype . 6.1.3
, , ,
Object.prototype. ,
new, prototype . ,
Object.create(),
( null).
ECMAScript 5
, Object.getPrototypeOf(). ECMA
Script3 ,
o o.constructor.prototype. ,
new, constructor,
-, .
, - prototype,
, .
9.2, ,
.
, , Object.cre
ate(), constructor, Object().

159

6.8.

, constructor.prototype
, , Object.create().
, (
) , isPrototypeOf().
, p o, p.isPrototypeOf(o).
:
var p = {x:1}; //
var o = Object.create(p); //
p.isPrototypeOf(o) //
Object.prototype.isPrototypeOf(p) //

-.
.
=> true: o p
=> true: p Object.prototype

, isPrototypeOf()
instanceof (4.9.4).
JavaScript Mozilla ( Netscape)
prototype __proto__,

. __proto__ :
(, , ) IE Opera,
Safari Chrome.
Firefox, ECMAScript5,
__proto__, .

6.8.2. class
class , .
ECMAScript3, ECMAScript5

. toString() ( Object.prototype)
:
[object class]

, ,
toString()
. ,
, toString(),
toString(), Func
tion.call() ( 8.7.3). 6.4 ,
, .
6.4. classof()
function classof(o) {
if (o === null) return "Null";
if (o === undefined) return "Undefined";
return Object.prototype.toString.call(o).slice(8,-1);
}

classof() , Ja
vaScript. , ,
toString(), null undefined
. (ECMAScript5 .) ,

160

6.

, Array Date,
class, .

class, . ,
Object.create, class Object.
, , ,
class Object:
class :
classof(null) //
classof(1) //
classof("") //
classof(false) //
classof({}) //
classof([]) //
classof(/./) //
classof(new Date()) //
classof(window) //
function f() {}; //
classof(new f()); //

=> "Null"
=> "Number"
=> "String"
=> "Boolean"
=> "Object"
=> "Array"
=> "Regexp"
=> "Date"
=> "Window" ( )

=> "Object"

6.8.3. extensible
extensible ,
. ECMAScript3
,
. ECMAScript5

, ,
-
.
ECMAScript 5
. ,
, Object.isExtensible().
, Object.preventExtensions().
, ,
. , preventExtensions()
.
,
.
extensible ,
, .
extensible con
figurable writable, ECMAScript5 ,
.
Object.seal() Object.preventExtensions(),
,
.
, .
, , - .

6.9.

161

Object.seal() .
, Object.seal() ,
Object.isSealed().
Object.freeze() .
, ,
,
. ( ,
; -
.) , Object.freeze()
, Object.isFrozen().
, Object.seal() Object.freeze()
, : .
, , ,
.
, Object.preventExtensions(), Object.seal() Object.freeze(),
, ,
:
// ,
// ,
var o = Object.seal(Object.create(Object.freeze({x:1}),
{y: {value: 2, writable: true}}));

6.9.

,
. JavaScript ECMA
Script5 JSON.stringify() JSON.parse().
JSON. JSON
JavaScript Object Notation ( JavaScript),

JavaScript:
o = {x:1, y:{z:[false,null,""]}}; //
s = JSON.stringify(o); // s == '{"x":1,"y":{"z":[false,null,""]}}'
p = JSON.parse(s); // p - o

ECMAScript5
ECMAScript3, http://json.org/json2.js.
,
ECMAScript 5 ECMAScript 3,
json2.js.
JSON Ja
vaScript
, JavaScript.
: , , , , true,
false null. NaN, Infinity -Infinity null.
Date ISO (

162

6.

Date.toJSON()), JSON.parse()
Date. Function, RegExp
Error undefined .
JSON.stringify()
. ,
. , JSON.stringify()
JSON.parse(), ,
/ ,
, , ,
.
.

6.10. Object
, JavaScript ( ,
) Object.prototype.

JavaScript, .
hasOwnProperty(), propertyIsEnumerable() isPrototy
peOf(). ( ,
Object, Object.create() Object.getPrototypeOf().)
,
Object.prototype
, .

6.10.1. toString()
toString() ; , -
, .
JavaScript ,
. , ,
+ ,
, .
toString() (
, 6.8.2).
, s
"[object Object]":
var s = { x:1, y:1 }.toString( );

,
toString(). ,
, ,
, ,
.
toString() . ,
, Array.toString(), Date.toString() Function.toString().
9.6.3 , toString()
.

6.10. Object

163

6.10.2. toLocaleString()
toString() toLocaleString().

. toLocaleString(),
Object, ; toString()
. Date Number
toLocaleString(),
. Array
toLocaleString(), toString()
,
toLocaleString(), toString().

6.10.3. toJSON()
Object.prototype toJSON(), JSON.
stringify() (6.9) toJSON()
, . ,
,
. Date.toJSON().

6.10.4. valueOf()
valueOf() toString(), ,
JavaScript -
, , . JavaScript
,
. valueOf() ,
,
valueOf() (, Date.valueOf()). 9.6.3 ,
valueOf() .

7
7.

.
,
, . JavaScript
: ,
.
,
, .
JavaScript
32- : 0,
4294967294 (232 2), ..
4294967295 . Ja
vaScript :
;

. JavaScript :
,
.
JavaScript length.
.
length .
JavaScript ,
, ,
.
.
,
,
.
Array.prototype,
,
7.8 7.9.

7.1.

165

, .. ,
, . , ,
7.11. ECMAScript5
, 7.12.

7.1.
,
.
:
var empty = []; //
var primes = [2, 3, 5, 7, 11]; //
var misc = [ 1.1, true, "a", ]; // 3 +


:
var base = 1024;
var table = [base, base+1, base+2, base+3];


:
var b = [[1,{x:1, y:2}], [2, {x:3, y:4}]];

c
, (
7.3). , , , undefined:
var count = [1,,3]; // 0 2. count[1] => undefined
var undefs = [,,]; // , , 2


, .. [,,] ,
.
Array().
:
:
var a = new Array();

, [].
,

:
var a = new Array(10);

.
Array()
,
. ,

166

7.

- 0, 1 ..
.

:
var a = new Array(5, 4, 3, 2, 1, "testing, testing");


. ,
Array().

7.2.
[].
.
, .
,
. , JavaScript-:
var a = ["world"]; //
var value = a[0]; //
a[1] = 3.14; //
i = 2;
a[i] = 3; //
a[i + 1] = "hello"; //
a[a[i]] = a[0]; //


0
1
2
3
0 2, 3

,
. , ,
, ,
. JavaScript
1 "1",
.
: :
o = {}; //
o[1] = "one"; //

, ,
, 232 2,
length. ,
a .
1, 2 3.
length :
a.length // => 4

.
, ,
0 232 2 .
, .
, ,
, length .

7.3.

167

,
. ,
.
,
, . ,
, ,
, .
, :
a[-1.23] = true; // "-1.23"
a["1000"] = 0; // 1001-
a[1.000] // 1. , a[1]

,
, , JavaScript
.
,
undefined. :
a = [true, false]; // 0 1
a[2] // => undefined. .
a[-1] // => undefined. .

,
. ECMAScript5
, (6.6).
,
:
.

7.3.
,
, 0. length
.
length .
Array()
, , .
a = new Array(5); // , a.length 5.
a = []; // length = 0.
a[1000] = 0; // , 1001.

,
delete.

, ,
, .
, ( , [1,,3]) ,
:

168

7.

var a1 = [,]; // , 1
var a2 = [undefined]; //
0 in a1 // => false: a1 0
0 in a2 // => true: a2 0 undefined

( Firefox 3) undefined . [1,,3] [1,undefined,3].

7.4.
length,
JavaScript. (.. )
length .
:
[].length // => 0:
['a','b','c'].length // => 3: 2, 3

length ,
, , , length
. ,
, ( ) ,
length .
.
: , i
length, length
i+1.
, length,
, length
n, , , ,
n, :
a = [1,2,3,4,5]; //
a.length = 3; //
a.length = 0; //
a.length = 5; //

.
a [1,2,3].
. a - [].
5, , Array(5)

length ,
. ,
.
ECMAScript 5 length
, Object.defineProperty() (6.7):
a = [1,2,3]; // a .
Object.defineProperty(a, "length", // length
{writable: false}); // .
a.length = 0; // a .

, ,
. , length
,

7.5.

169

. ( 6.7, Object.seal() Object.freeze()


6.8.3.)

7.5.
,
, :
a = [] // .
a[0] = "zero"; // .
a[1] = "one";


push():
a = []; //
a.push("zero") // . a = ["zero"]
a.push("one", "two") // . a = ["zero", "one", "two"]

,
a[a.length].
unshift() ( 7.8),
.
delete,
:
a = [1,2,3];
delete a[1]; // a 1
1 in a // => false: 1
a.length // => 3: delete length

( )
undefined . ,
delete length
, ,
.
.
, ,
length.
pop() ( push()),
1 .
shift() ( unshift()),
. delete, shift()
. pop() shift()
7.8 .
splice(), ,
. length

. 7.8.

170

7.

7.6.
for (5.5.3):
var keys = Object.keys(o); // o
var values = [] //
for(var i = 0; i < keys.length; i++) { //
var key = keys[i]; //
values[i] = o[key]; // values
}

,
,
,
, :
for(var i = 0, len = keys.length; i < len; i++) {
//
}

,
.
.
null, undefined
, :
for(var i = 0; i < a.length; i++) {
if (!a[i]) continue; // null, undefined .
//
}

undefined
, :
for(var i = 0; i < a.length; i++) {
if (a[i] === undefined) continue; // undefined + . .
//
}

, ,
undefined ,
:
for(var i = 0; i < a.length; i++) {
if (!(i in a)) continue ; //
//
}

for/in (
5.5.4). (
) . :
for(var index in sparseArray) {
var value = sparseArray[index];
//
}

7.7.

171

6.5, for/in
, , Array.prototype.
for/in ,
.
, , :
for(var i in a) {
if (!a.hasOwnProperty(i)) continue; //
//
}
for(var i in a) {
// i,
if (String(Math.floor(Math.abs(Number(i)))) !== i) continue;
}

ECMAScript
for/in .
, . ,
, ,
, .
- , ,
, for/in
for.
ECMAScript5 ,

, .
forEach():
var data = [1,2,3,4,5]; //
var sumOfSquares = 0; //
data.forEach(function(x) { //
sumOfSquares += x*x; //
});
sumOfSquares // =>55 : 1+4+9+16+25

forEach() ,
,
. 7.9,
8.8,
.

7.7.
JavaScript ,
.
[].
, , matrix .
matrix[x] .
matrix[x][y].
,
:

172

7.

//
var table = new Array(10); // 10
for(var i = 0; i < table.length; i++)
table[i] = new Array(10); // 10
//
for(var row = 0; row < table.length; row++) {
for(col = 0; col < table[row].length; col++) {
table[row][col] = row*col;
}
}
// 5*7
var product = table[5][7]; // 35

7.8. Array
ECMAScript3 Array.prototype
,
. .
Array
JavaScript. ECMAScript5
7.9.

7.8.1. join()
Array.join() ,
.
,
. - , .
, 1,2,3:
var a = [1, 2, 3]; //
a.join(); //
a.join(" "); //
a.join(""); //
var b = new Array(10); //
b.join('-') //


=> "1,2,3"
=> "1 2 3"
=> "123"
, 10,
=> '---------': 9

Array.join() String.split(),
.

7.8.2. reverse()
Array.reverse()
.
, ..
,
. , , reverse()
join(), "3,2,1":
var a = [1,2,3];
a.reverse().join(); // => "3,2,1": a = [3,2,1]

7.8. Array

173

7.8.3. sort()
Array.sort()
. sort() ,
(
, ):
var a = new Array("banana", "cherry", "apple");
a.sort();
var s = a.join(", "); // s == "apple, banana, cherry"

.
- , ,
sort() .
,
. ,
.
,
. (..
), 0. , ,
:
var a = [33, 4, 1111, 222];
a.sort(); // : 1111, 222, 33, 4
a.sort(function(a,b) { // : 4, 33, 222, 1111
return a-b; // < 0, 0 > 0
}); // a b
a.sort(function(a,b) {return b-a}); //

,
. ,
.

,
, (
toLowerCase()) .
a = ['ant', 'Bug', 'cat', 'Dog']
a.sort(); // : ['Bug','Dog','ant',cat']
a.sort(function(s,t) { //
var a = s.toLowerCase();
var b = t.toLowerCase();
if (a < b) return -1;
if (a > b) return 1;
return 0;
}); // => ['ant','Bug','cat','Dog']

7.8.4. concat()
Array.concat() ,
, concat(),
, concat(). -
, . ,
, ,

174

7.

. concat() .
:
var a = [1,2,3];
a.concat(4, 5) //
a.concat([4,5]); //
a.concat([4,5],[6,7]) //
a.concat(4, [5,[6,7]]) //

[1,2,3,4,5]
[1,2,3,4,5]
[1,2,3,4,5,6,7]
[1,2,3,4,5,[6,7]]

7.8.5. slice()
Array.slice() , , .
.
,
, , ( ) ,
. ,

. - ,
. , 1
, 3
. :
var a = [1,2,3,4,5];
a.slice(0,3); //
a.slice(3); //
a.slice(1,-1); //
a.slice(-3,-2); //

[1,2,3]
[4,5]
[2,3,4]
[3]

7.8.6. splice()
Array.splice() ,
. slice() concat(), splice()
, .
, splice() slice() ,
.
splice() ,
.
,
. splice()
, / .
, (
) . ,
. splice()
( ) . :
var a = [1,2,3,4,5,6,7,8];
a.splice(4); // [5,6,7,8]; a = [1,2,3,4]
a.splice(1,2); // [2,3]; a = [1,4]
a.splice(1,1); // [4]; a = [1]

splice() ,
.

175

7.8. Array

, ,
, , . :
var a = [1,2,3,4,5];
a.splice(2,0,'a','b'); // []; a = [1,2,'a','b',3,4,5]
a.splice(2,2,[1,2],3); // ['a','b']; a = [1,2,[1,2],3,3,4,5]

, , concat(), splice()
, .

7.8.7. push() pop()


push() pop() .
push()
. pop()
,
. , ,
. push() pop()

. :
var stack = []; //
stack.push(1,2); //
stack.pop(); //
stack.push(3); //
stack.pop(); //
stack.push([4,5]); //
stack.pop() //
stack.pop(); //

:
:
:
:
:
:
:
:

[]
[1,2]
[1]
[1,3]
[1]
[1,[4,5]]
[1]
[]

2
2
2
3
2
[4,5]
1

7.8.8. unshift() shift()


unshift() shift() , push() pop(),
, , .
unshift()
,
. shift()
, ,
, . :
var a = []; //
a.unshift(1); //
a.unshift(22); //
a.shift(); //
a.unshift(3,[4,5]); //
a.shift(); //
a.shift(); //
a.shift(); //

a:[]
a:[1] :
a:[22,1] :
a:[1] :
a:[3,[4,5],1] :
a:[[4,5],1] :
a:[1] :
a:[] :

1
2
22
3
3
[4,5]
1

unshift()
. , (
splice()). ,
, .
, .

176

7.

7.8.9. toString() toLocaleString()


, JavaScript, toString().
(
toString() )
. ,
- . :
[1,2,3].toString() // '1,2,3'
["a", "b", "c"].toString() // 'a,b,c'
[1, [2,'c']].toString() // '1,2,c'

, toString() , join()
.
toLocaleString() toString().
toLocaleString() ,

( ) .

7.9. Array,
ECMAScript5
ECMAScript 5 ,
, , , ,
. .
, ,
, ECMAScript5. -,

( ) .

.
: , .
,
. ,
ECMAScript5, ,
. ,
, .
, this.
, , ,
-. , ECMA
Script5, . , ,
, .

7.9.1. forEach()
forEach()
. ,
forEach() . forEach()
: ,

7.9. Array, ECMAScript5

177

. ,
:
var data = [1,2,3,4,5]; // ,
//
var sum = 0; // 0
data.forEach(function(value) { sum += value; }); // sum
sum // => 15
// 1
data.forEach(function(v, i, a) { a[i] = v + 1; });
data // => [2,3,4,5,6]

, forEach() ,
.
break, for.
, ,
forEach() try. foreach(),
forEach() try. ,
foreach(), foreach.break,
:
function foreach(a,f,t) {
try { a.forEach(f,t); }
catch(e) {
if (e === foreach.break) return;
else throw e;
}
}
foreach.break = new Error("StopIteration");

7.9.2. map()
map() ,
, ,
. :
a = [1, 2, 3];
b = a.map(function(x) { return x*x; }); // b = [1, 4, 9]

map() , forEach().
, map(), .
, map() : .
,
:
.

7.9.3. filter()
filter() ,
. -,
.. true false. filter()
, forEach() map(). true
, true,

178

7.

, .
:
a = [5, 4, 3, 2, 1];
smallvalues = a.filter(function(x) { return x < 3 }); // [2, 1]
everyother = a.filter(function(x,i) { return i%2==0 }); // [5, 3, 1]

, filter()
.
, :
var dense = sparse.filter(function() { return true; });

undefined
null, filter(), :
a = a.filter(function(x) { return x !== undefined && x != null; });

7.9.4. every() some()


every() some() :
- true false.
every() : true,
- true
:
a = [1,2,3,4,5];
a.every(function(x) { return x < 10; }) // => true: < 10.
a.every(function(x) { return x % 2 === 0; }) // => false: .

some() :
true, , true, false ,
- false :
a = [1,2,3,4,5];
a.some(function(x) { return x%2===0; }) // => true: .
a.some(isNaN) // => false: .

, , every() some(),
, . some()
true, - true,
, - false.
every() : false,
- false, ,
- true. , ,
every()
true, some() false.

7.9.5. reduce() reduceRight()


reduce() reduceRight() ,
, .
,
. :

7.9. Array, ECMAScript5


var
var
var
var

179

a = [1,2,3,4,5]
sum = a.reduce(function(x,y) { return x+y }, 0); //
product = a.reduce(function(x,y) { return x*y }, 1); // .
max = a.reduce(function(x,y) { return (x>y)?x:y; }); // .

reduce() . ,
.
.
, ,
. ()
.
, reduce(), ,
forEach() map(). ,
, .
.
, reduce()
. ,
. , ,
0 1.
1. 1 2 3.
3+3=6, 6+4=10 , , 10+5=15.
15 reduce().
, , , ,
reduce() :
. reduce() ,
, .
,
.
.
reduce()
TypeError. ,
,
,
.
reduceRight() , reduce(),
, ,
( ). ,
, :
var a = [2, 3, 4]
// 2^(3^4).
var big = a.reduceRight(function(accumulator,value) {
return Math.pow(value,accumulator);
});

, reduce(), reduceRight()
, this .
.
,
Function.bind().

180

7.

, every() some(), ,
.
reduce() ,
.
, ,
, reduce() reduceRight()
. union() 6.2.
,
.
, .. ,
reduce()
:
var objects = [{x:1}, {y:2}, {z:3}];
var merged = objects.reduce(union); // => {x:1, y:2, z:3}

, , ,
union() , .. reduce() redu
ceRight() union():
var objects = [{x:1,a:1}, {y:2,a:2}, {z:3,a:3}];
var leftunion = objects.reduce(union); // {x:1, y:2, z:3, a:3}
var rightunion = objects.reduceRight(union); // {x:1, y:2, z:3, a:1}

7.9.6. indexOf() lastIndexOf()


indexOf() lastIndexOf()
1,
. indexOf()
, lastIndexOf() .
a = [0,1,2,1,0];
a.indexOf(1) // => 1: a[1] = 1
a.lastIndexOf(1) // => 3: a[3] = 1
a.indexOf(3) // => -1: 3

, , indexOf() last
IndexOf() .
. :
, .
, indexOf() , lastIndexOf()
. ,
,
splice(): 1, , .

, . ,
indexOf()
.
// x
//
function findall(a, x) {

181

7.10. Array
var results = [], //
len = a.length, //
pos = 0; //
while(pos < len) { //
pos = a.indexOf(x, pos); //
if (pos === -1) break; //
results.push(pos); //
pos = pos + 1; //
}
return results; //
}


,

...

, .
-

, indexOf() lastIndexOf(),
.

7.10. Array
,
, .
, , .
ECMAScript5 Array.isArray():
Array.isArray([]) // => true
Array.isArray({}) // => false

ECMAScript5
. typeof :
object ( , ).
instanceof:
[] instanceof Array // => true
({}) instanceof Array // => false

instanceof , -
.
JavaScript, .
-.

. ,
, ,
instanceof .
, class (
6.8.2) .
Array, ECMAScript3 isArray()
:
var isArray = Function.isArray || function(o) {
return typeof o === "object" &&
Object.prototype.toString.call(o) === "[object Array]";
};

class Array.
isArray(), ECMAScript 5.

182

7.

Object.prototype.toString() 6.8.2
6.4.

7.11. ,
, JavaScript
, :

length.
length .
Array.prototype.
class Array.
JavaScript
. , .
,
length .
, ,
,
length,
,
. ,
,
. ,
length.

, , ,
:
var a = {}; //
// ,
var i = 0;
while(i < 10) {
a[i] = i * i;
i++;
}
a.length = i;
//
var total
for(var j
total

,
= 0;
= 0; j < a.length; j++)
+= a[j];

Arguments, 8.3.2, ,
. JavaScript
(DOM), docu
ment.getElementsByTagName(). ,
:

7.11. ,

183

// , o , .
// length, typeof.
// JavaScript DOM length
// , , o.nodeType != 3.
function isArrayLike(o) {
if (o && // o null, undefined ..
typeof o === "object" && // o -
isFinite(o.length) && // o.length -
o.length >= 0 && // o.length -
o.length===Math.floor(o.length) && // o.length -
o.length < 4294967296) // o.length < 2^32
return true; // , o
else
return false; // -
}

7.12 , ECMAScript5
(
ECMAScript5).
, , false
, .
JavaScript
,
, , . ECMAScript5
. ECMAScript 3
, toString() toLocaleString(). (
concat():
, ,
.) , ,
Array.prototype, .
, Function.call():
var a = {"0":"a", "1":"b", "2":"c", length:3}; // ,
Array.prototype.join.call(a, "+") // => "a+b+c"
Array.prototype.slice.call(a, 0) // => ["a","b","c"]: ,
Array.prototype.map.call(a, function(x) {
return x.toUpperCase();
}) // => ["A","B","C"]:

call() 7.10,
isArray(). call() Function
8.7.3.
, ECMAScript5, Firefox1.5.
, Firefox
,
Array. ,
:
var a = {"0":"a", "1":"b", "2":"c", length:3}; // ,
Array.join(a, "+")
Array.slice(a, 0)
Array.map(a, function(x) { return x.toUpperCase(); })

184

7.


, , , ,
, .
,
:
Array.join = Array.join || function(a,sep) {
return Array.prototype.join.call(a,sep);
};
Array.slice = Array.slice || function(a,from,to) {
return Array.prototype.slice.call(a,from,to);
};
Array.map = Array.map || function(a, f, thisArg) {
return Array.prototype.map.call(a, f, thisArg);
}

7.12.
ECMAScript5 ( , IE8,
ECMAScript5)
, . charAt()
:
var s = test;
s.charAt(0) // => "t"
s[1] // => "e"

typeof string,
Array.isArray(), false.
, ,
charAt()
, , ,
. , ,
, .
:
s = "JavaScript"
Array.prototype.join.call(s, " ") //
Array.prototype.filter.call(s, //
function(x) {
return x.match(/[^aeiou]/); //
}).join("") //

=> "J a v a S c r i p t"




=> "JvScrpt"

, ,
,
. , push(), sort(), reverse()
splice(), .
:
.

8
8.

JavaScript,
, , . ,
,
, . :
,
.
, , .

, .
,
this.
,
. ,
, this. ,
,
. 6.1, 9.
JavaScript
. ,
. ,
.
JavaScript ,
, ,
. JavaScript
,
.

8.1.
function,
(4.3)

186

8.

(5.3.2).
function,
:
, .
:
, .
:
.
,
.
.
JavaScript .
:
.
8.1
. ,
,
, ,
.



. ,
.
.
(,
) .
,
.
. ,

, : like_this(),
, , , : likeThis().
, , , ,
,
.


.
jQuery JavaScript ( 19),
$() (-, ).
(2.4 , JavaScript
-
.)

8.1.

187

8.1. JavaScript-
// o. undefined.
function printprops(o) {
for(var p in o)
console.log(p + ": " + o[p] + "\n");
}
// (x1,y1) (x2,y2).
function distance(x1, y1, x2, y2) {
var dx = x2 - x1;
var dy = y2 - y1;
return Math.sqrt(dx*dx + dy*dy);
}
// ( ),
// , x! - x , x.
function factorial(x) {
if (x <= 1) return 1;
return x * factorial(x-1);
}
// , .
// ,
var square = function(x) { return x*x; }
// ,
// .
var f = function fact(x) { if (x <= 1) return 1; else return x*fact(x-1); };
//
// :
data.sort(function(a,b) { return a-b; });
// :
var tensquared = (function(x) {return x*x;}(10));

,
.
. ,
, .
, ,
.
,
.
, .
,
.
,
.
5.3.2,
,

. ,
: ,

188

8.

, ,
, .
(3.10.1),
, ,
, , .
, ( ) 8.1
return (5.6.4). return
( )
. return ,
undefined. return ,

undefined.
8.1 ,
return
. printprops() :
, .
- , return.
printprops() undefined. (,
, .)

8.1.1.
JavaScript .
:
function hypotenuse(a, b) {
function square(x) { return x*x; }
return Math.sqrt(square(a) + square(b));
}


: ,
( ). ,
square() a b,
hypotenuse(). ,
, , 8.6.
5.3.2,
, ECMAScript
.
,
, , try/
catch/finally with.1 ,
function.

JavaScript.
1

JavaScript . ,
Firefox
if.

8.2.

189

8.2.
, ,
, . JavaScript
:
,
,

, call() apply().

8.2.1.
,
( 4.5).
, ,
-,
, .

.
.
:
printprops({x:1});
var total = distance(0,0,2,1) + distance(2,1,3,5);
var probability = factorial(5)/factorial(13);

- (
),
. ,
.
.

.
, undefined.
return,
, return, undefined,
return .
ECMAScript3 ECMAScript5
( this) .
undefined.
,
, this. ,
, , :
// , .
var strict = (function() { return !this; }());

190

8.


,
, ,
. (,
) .
jQuery (19), , :
// , id,
//
$(":header").map(function() { return this.id }).get().sort();

,
, this.
API,
,
,1
, :
shape.setX(100).setY(100).setSize(50).setOutline("red").setFill("blue").draw();

,
9.7.2.

8.2.2.
, ,
. f o, o
m, :1
o.m = f;

m() o:
o.m();

, m() , :
o.m(x, y);

:
o.m -, x y.
( 4.4),
, , .

, .
: .
: ( o) (m).
1

(Martin Fowler). . http://martinfowler.com/


dslwip/MethodChaining.html.

8.2.

191

o ,
this.
:
var calculator = { //
operand1: 1,
operand2: 1,
add: function() {
// ,
// this.
this.result = this.operand1 + this.operand2;
}
};
calculator.add(); // , 1+1.
calculator.result // => 2


,
. ,
:
o["m"](x,y); // : o.m(x,y).
a[0](z) // (, a[0] - ).


:
customer.surname.toUpperCase(); // customer.surname
f().m(); // m() f()

this
- . ,
, ,
. ,
, ,
. :
rect.setSize(width, height);
setRectSize(rect, width, height);

, ,
rect (),
,
rect.
: this ,
. JavaScript
this.
, this ,
this .
, this ,
.
, this (
), undefined ( ). ,

192

8.

, ,
this .
this ,
,
.
self. :
var o = { //
m: function() { //
var self = this; //
console.log(this === o); //
f(); //

o.
m .
this .
"true": this - o.
- f().

function f() { //
console.log(this === o); //
console.log(self === o); //
}
}
};
o.m(); //

f
"false": this - . . undefined
"true": self - . this . -.

m o.

8.5 (8.7.4)
var self=this.

8.2.3.
new,
, . ( 4.6
6.1.2, 9.)

, .
,
- ,
. ,
JavaScript
.
. , :
var o = new Object();
var o = new Object;

, proto
type . -
,
, -
this. ,
,
. new o.m()
, o.
, - return.

, .

8.3.

193

.
return,
. return
,

.

8.2.4.
JavaScript
. , call() apply(),
. this
,
,
. , . call()

, apply() ,
. call() apply()
8.7.3.

8.3.
JavaScript, ,

. JavaScript
. ,
,
. ,
, ,
.

8.3.1.

, undefined.
,
.

, . :
// a o .
// a , .
function getPropertyNames(o, /* */ a) {
if (a === undefined) a = []; // ,
for(var property in o) a.push(property);
return a;
}
// 1 2 :
var a = getPropertyNames(o); // o
getPropertyNames(p,a); // p

194

8.

if
|| :
a = a || [];

4.10.2 , || ,
, .
, - ,
. (
null), .
,
, .
, ,
:
undefined.
/* */ , ,
.

8.3.2. :
Arguments
,

. Arguments.
arguments Arguments,
. Arguments , (7.11),
, .
, f, , x.
,
x arguments[0].
arguments[1]. , , argu
ments length, .
f, , arguments.length
2.
Arguments .
, ,
, JavaScript :
function f(x, y, z)
{
// ,
if (arguments.length != 3) {
throw new Error(" f " + arguments.length +
", 3.");
}
// ...
}

,
, . Java

8.3.

195

Script :
undefined, .
Arguments JavaScript-:
,
.
(
Math.max()):
function max(/*...*/)
{
var m = Number.NEGATIVE_INFINITY;
// ,
for(var i = 0; i < arguments.length; i++)
if (arguments[i] > max) max = arguments[i];
//
return max;
}
var largest = max(1, 10, 100, 2, 3, 1000, 4, 5, 10000, 6); // => 10000

,
, (variadic func
tions, variable arity functions varargs functions).
C.
,
.
arguments[] ,
,

.
, arguments
Arguments. Arguments
length, .
, .
, , 7.11.
Arguments .
, Arguments
,
. arguments[]
.
, arguments[].
arguments[] ,
. :
function f(x) {
console.log(x); //
arguments[0] = null; // x!
console.log(x); // "null"
}

196

8.

, ,
. arguments[0] x
, .
Arguments
, ECMAScript5. ,
. arguments
JavaScript-, .
arguments

arguments.

8.3.2.1. callee caller


Arguments callee
caller. ECMA
Script5 TypeError.
ECMAScript , callee
. caller
, ,
. caller
, callee
:
var factorial = function(x) {
if (x <= 1) return 1;
return x * arguments.callee(x-1);
};

8.3.3.

,
.
,
,
/
. ,
.
,
/.
,
:
// length from to.
// from_start from
// , to_start to.
// .
function arraycopy(/* */ from, /* */ from_start,
/* */ to, /* */ to_start,
/* */ length)
{

8.3.

197

//
}
// ,
// , from_start to_start 0.
function easycopy(args) {
arraycopy(args.from,
args.from_start || 0, // ,
args.to, //
args.to_start || 0,
args.length);
}
// easycopy():
var a = [1,2,3,4], b = [];
easycopy({from: a, to: b, length: 4});

8.3.4.
JavaScript ,

. ,

,
arraycopy().
(optional).
, :
function max(/* ... */) { /* */ }

3.8, JavaScript
. , ,
, -
, ,
.
, toString() (,
); .
. array
copy(), .
. ,
(, , , ).
, - ,
.
, ,
, .
, .
, isArrayLike() 7.11:
// ( , ) a.
// , null
// undefined .
function sum(a) {
if (isArrayLike(a)) {

198

8.

var total = 0;
for(var i = 0; i < a.length; i++) { //
var element = a[i];
if (element == null) continue; // null undefined
if (isFinite(element)) total += element;
else throw new Error("sum(): ");
}
return total;
}
else throw new Error("sum(): ");
}

sum()
,
.
, ,
, , null undefined.
JavaScript ,
,
. flexsum(),
(, , ).
,
, .
. ,
, ,
:
function flexisum(a) {
var total = 0;
for(var i = 0; i < arguments.length; i++) {
var element = arguments[i], n;
if (element == null) continue; // null undefined
if (isArray(element)) // -
n = flexisum.apply(this, element); //
else if (typeof element === "function") // , ...
n = Number(element()); // .
else n = Number(element); //
if (isNaN(n)) // , .
throw Error("flexisum(): " + element +
" ");
total += n; // n total
}
return total;
}

8.4.
,
.
JavaScript . Ja
vaScript , ,

199

8.4.

, ,
, ..1
, JavaScript
, :
function square(x) { return x*x; }


square.
, .
, , :
var s = square; // s , square
square(4); // => 16
s(4); // => 16

,
. :
var o = {square: function(x) { return x*x; }}; //
var y = o.square(16); // y = 256

, ,
:
var a = [function(x) { return x*x; }, 20]; //
a[0](a[1]); // => 400

,
!
8.2 , ,
. ,
, .
8.2.
//
function add(x,y) { return x + y;
function subtract(x,y) { return x
function multiply(x,y) { return x
function divide(x,y) { return x /

}
- y; }
* y; }
y; }

//
//
function operate(operator, operand1, operand2)
{
return operator(operand1, operand2);
}
// (2+3)+(4*5):
var i = operate(add, operate(add, 2, 3), operate(multiply, 4, 5));

, ,
Java, ,
.

200

8.

// ,
// .
var operators = {
add: function(x,y) { return x+y; },
subtract: function(x,y) { return x-y; },
multiply: function(x,y) { return x*y; },
divide: function(x,y) { return x/y; },
pow: Math.pow //
};
// , ,
// .
// .
function operate2(operation, operand1, operand2)
{
if (typeof operators[operation] === "function")
return operators[operation](operand1, operand2);
else throw " ";
}
// ("hello" + " " + "world"):
var j = operate2("add", "hello", operate2("add", " ", "world"));
// Math.pow():
var k = operate2("pow", 10, 2);


Array.sort(). .
(, , , ,
..), sort()
, , .
: ,
, , .
- Array.sort()

. Array.sort() 7.8.3.

8.4.1.
JavaScript ,
, .
,
,
,
. , , ,
.
. ,

.
, ,
. Function.
,
:

8.5.

201

// counter .
// , .
uniqueInteger.counter = 0;
// .
// .
function uniqueInteger() {
return uniqueInteger.counter++; // counter
}

, factorial(),
( )
:
// .
function factorial(n) {
if (isFinite(n) && n>0 && n==Math.round(n)) { //
if (!(n in factorial)) //
factorial[n] = n * factorial(n-1); //
return factorial[n]; // .
}
else return NaN; //
}
factorial[1] = 1; // .

8.5.
3.10.1 , JavaScript ,
: , ,
( ),
. ,
, JavaScript. JavaScript ,
,
,
, ,
.
, , JavaScript,
JavaScript- (,
JavaScript, -). ,
, ,
.
,
, ,
, , ,
, . ,
.

:
function mymodule() {
// .

202

8.

// , ,
// .
}
mymodule(); // !

:
mymodule. ,
:
(function() { // mymodule
// .
}()); // .


, .
.
function ,
function .

. ,
, ,
.

8.3. ,
extend(), , 6.2.
Internet Explorer
, . ,
, .
8.3. extend(), ,
// extend,
// . IE: IE for/in
// o,
// . , ,
// toString, , .
var extend = (function() { // ,
// , .
for(var p in {toString:null}) {
// , , for/in
// extend()
return function extend(o) {
for(var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for(var prop in source) o[prop] = source[prop];
}
return o;
};
}
// , , for/in
// toString . extend(),
// Object.prototype.

// ,

8.6.

203

var protoprops = ["toString", "valueOf", "constructor", "hasOwnProperty",


"isPrototypeOf", "propertyIsEnumerable", "toLocaleString"];
return function patched_extend(o) {
for(var i = 1; i < arguments.length; i++) {
var source = arguments[i];
//
for(var prop in source) o[prop] = source[prop];
//
for(var j = 0; j < protoprops.length; j++) {
prop = protoprops[j];
if (source.hasOwnProperty(prop)) o[prop] = source[prop];
}
}
return o;
};
}());

8.6.
, JavaScript
. ,
,
, .
JavaScript
,
. ( ,
, ,
3.10 3.10.3.)
(
), , ,
.1
JavaScript :
.
,
,
.
,
, , .
,
, .
, -,

JavaScript.
, ,
.
1

, ,
,
.

204

8.


, .
( 3.10):
var scope = "global scope"; //
function checkscope() {
var scope = "local scope"; //
function f() { return scope; } //
return f();
}
checkscope() //



scope

=> "local scope"


,
:
,
.
,
. , , ,
,
,
, ?
, ,
, C,
, :
,
.
3.10.3.
, . ,
JavaScript ,
,
. ,
.
,
. ,
,
.

, ,
,
.
- ,
.
,
,
.

205

8.6.

checkscope() ,
. ,
checkscope() local scope.
. , ?
var scope = "global scope"; //
function checkscope() {
var scope = "local scope"; //
function f() { return scope; } //
return f;
}
checkscope()() //



scope

checkscope()
. check
scope() .
, (
) - , ?
:
JavaScript ,
. f()
, scope local scope.
f, ,
.
local scope, global scope. ,
:
() , .
8.4.1 uniqueInteger(),

. ,

, uniqueInteger()
.

. ,
uniqueInteger() :
var uniqueInteger = (function() { //
var counter = 0; //
return function() { return counter++; };
}());

, , .
,
uniqueInteger. (
),
uniqueInteger ,
. , ,
.
uniqueInteger.
counter,

206

8.

.
counter:
.
, counter,
:
,
.
:
function counter() {
var n = 0;
return {
count: function() { return n++; },
reset: function() { n = 0; }
};
}
var c = counter(), d = counter(); //
c.count() //
d.count() //
c.reset() //
//
c.count() //
d.count() //


=> 0
=> 0:
reset() count()

=> 0: c
=> 1: d

counter() . :
count(), , reset(),
. ,
n. -,
counter()
. , counter() ,
- .
count() reset() - .
,
.
counter() ,
6.6,
:
function counter(n) { // n -
return {
// .
get count() { return n++; },
// n
set count(m) {
if (m >= n) n = m;
else throw Error(" ");
}
};
}
var c = counter(1000);
c.count // => 1000

8.6.

207

c.count // => 1001


c.count = 2000
c.count // => 2000
c.count = 2000 // => !

, counter()
. n,
. ,
counter(), .
8.4
. addPriva
teProperty(),
.
:
8.4.

// o.
// get<name> set<name>.
// ,
// . false,
// .
//
// , ,
// , o,
// . ,
// .
// ,
// , .
function addPrivateProperty(o, name, predicate) {
var value; //
// .
o["get" + name] = function() { return value; };
// ,
// .
o["set" + name] = function(v) {
if (predicate && !predicate(v))
throw Error("set" + name + ": " + v);
else
value = v;
};
}
// addPrivateProperty().
var o = {}; //
// getName() setName()
//
addPrivateProperty(o, "Name", function(x) { return typeof x == "string"; });
o.setName("Frank"); //
console.log(o.getName()); //
o.setName(0); //

208

8.

,

. ,
,
. :
// , v
function constfunc(v) { return function() { return v; }; }
// -:
var funcs = [];
for(var i = 0; i < 10; i++) funcs[i] = constfunc(i);
// 5 5.
funcs[5]() // => 5

,
, , ,
. , :
// , 0-9
function constfuncs() {
var funcs = [];
for(var i = 0; i < 10; i++)
funcs[i] = function() { return i; };
return funcs;
}
var funcs = constfuncs();
funcs[5]() // ?

10 .
,
i. constfuncs() , i
10, 10 .
,
, , . ,
, , .

.
, , this
, . ,
this, this
, :
var self = this; // this
// .

arguments. ,
.
arguments,
,
:
var outerArguments = arguments; //

8.7. Function

209

8.5, , ,
this arguments .

8.7.
Function
, JavaScript-
. typeof function,
JavaScript .
, ,
. Function(),
.
, Function(). ,
.

8.7.1. length
arguments.length ,
. length .
, , ,
, .
check(),
arguments . argu
ments.length ( ) arguments.
callee.length ( ), ,
, . ,
. check() f(),
check():
// arguments.callee,
// .
function check(args) {
var actual = args.length; //
var expected = args.callee.length; //
if (actual !== expected) // ,
throw new Error(": " + expected + "; " + actual);
}
function f(x, y, z) {
// .
check(arguments);
//
return x + y + z;
}

8.7.2. prototype
prototype, ,
. .
,

210

8.

. prototype
6.1.3, 9.

8.7.3. call() apply()


call() apply() (
8.2.4), . (
call() 6.4 Object.prototype.toString
, .)
, call() apply(), ,
;
this . f() ( )
o, , call() apply():
f.call(o);
f.apply(o);

(
, o m):
o.m = f; // f o.
o.m(); // .
delete o.m; // .

ECMAScript5 call() apply()


this, , null undefined. ECMA
Script3 null undefined
, -.
call(), ,
, . ,
, f() ,
o:
f.call(o, 1, 2);

apply() call(), ,
:
f.apply(o, [1,2]);

,
apply()
. ,
, Math.max()
apply():
var biggest = Math.max.apply(Math, array_of_numbers);

, apply()
, , . ,
, ,
apply(). :
// m o ,
// .

8.7. Function

211

function trace(o, m) {
var original = o[m]; // .
o[m] = function() { // .
console.log(new Date(), "Entering:", m); // .
var result = original.apply(this, arguments); // .
console.log(new Date(), "Exiting:", m); // .
return result; // .
};
}

trace() .
,
.
(monkey-patching).

8.7.4. bind()
bind() ECMAScript5, ECMA
Script 3. , bind()
, (bind) . bind()
f o, .
( ) f
o. , ,
. :
function f(y) { return this.x + y; } //
var o = { x : 1 }; //
var g = f.bind(o); //
g(2) //

,
,
g(x) o.f(x)
=> 3

ECMAScript3, :
// , f o
// .
function bind(f, o) {
if (f.bind) return f.bind(o); // bind,
else return function() { // ,
return f.apply(o, arguments);
};
}

bind() ECMAScript5 .
: this
, bind() .

(currying).
bind() :
var sum = function(x,y) { return x + y }; // 2
// , sum, null
// this , 1.
// .
var succ = sum.bind(null, 1);
succ(2) // => 3: x 1, 2 . y

212

8.

function f(y,z) { return this.x + y + z }; //


var g = f.bind({x:1}, 2); // this y
g(3) // => 6: this.x - 1, y - 2, 3 z

ECMAScript3 this
. bind()
, 8.5. ,
Function.prototype.bind,
. 9.4.
8.5. Function.bind() ECMAScript3
if (!Function.prototype.bind) {
Function.prototype.bind = function(o /*, */) {
// this arguments ,
// .
var self = this, boundArgs = arguments;
// bind() -
return function() {
// ,
// bind, .
var args = [], i;
for(i = 1; i < boundArgs.length; i++) args.push(boundArgs[i]);
for(i = 0; i < arguments.length; i++) args.push(arguments[i]);
// self o
return self.apply(o, args);
};
};
}

, , bind(),
, self boundArgs,
,
, -
.
bind(), ECMAScript5,
, ECMAScript3. ,
bind() , length
,
( ). -, bind()
ECMAScript5 -
. , bind(),
, this, bind(), ,
, ,
. , bind(),
prototype ( prototype ), ,
-, proto
type , . ,
instanceof ,
.

8.7. Function

213

8.7.5. toString()
JavaScript, toString().
ECMAScript , ,
.
( ) toString()
. ,
[native code] .

8.7.6. Function()
function
, -.
Function().
:
var f = new Function("x", "y", "return x*y;");

,
, :
var f = function(x, y) { return x*y; }

Function() .
;
JavaScript,
.
. , ,
.
, Function() ,
. ,
Function() .
, Function(),
:
Function()
.
Function()
.
,
. ,

.
, :
Function(),
,
:
var scope = "";
function constructFunction() {
var scope = "";

214

8.
return new Function("return scope"); //
// !
}
// "", ,
// Function(), .
constructFunction()(); // => ""

Function() eval() (
4.12.2),
.
.

8.7.7.
7.11 , , ,
,
. .
,
. ,
.
, ,
JavaScript . -, - IE ( 8
) , Window.alert() Document.getEle
mentsById(), , Function.
IE , ,
Function. IE9
,
.

RegExp
RegExp, exec().
JavaScript.
Netscape
. ,
RegExp: , ,
. typeof
RegExp.
function, object.
,
( ), ,
class ( 6.8.2), ,
6.4:
function isFunction(x) {
return Object.prototype.toString.call(x) === "[object Function]";
}

, isFunction()
isArray(), 7.10.

8.8.

215

8.8.
JavaScript , Lisp
Haskell, , JavaScript
, JavaScript
. ECMAScript 5,
map() reduce(),
.
JavaScript.

, JavaScript.1

8.8.1.
,
.
,
:
var data = [1,1,3,5,5]; //
// - ,
var total = 0;
for(var i = 0; i < data.length; i++) total += data[i];
var mean = total/data.length; // 3
// ,
// .
total = 0;
for(var i = 0; i < data.length; i++) {
var deviation = data[i] - mean;
total += deviation * deviation;
}
var stddev = Math.sqrt(total/(data.length-1)); // = 2

,
map() reduce(), (
7.9):
//
var sum = function(x,y) { return x+y; };
var square = function(x) { return x*x; };
// Array
//
var data = [1,1,3,5,5];
var mean = data.reduce(sum)/data.length;
var deviations = data.map(function(x) {return x-mean;});
var stddev = Math.sqrt(deviations.map(square).reduce(sum)/(data.length-1));

, ,
( ) Functional JavaScript (Oliver Ste
el), : http://osteele.com/sources/javascript/functional/.

216

8.

, ECMA
Script3, ?
map() reduce(),
:
// f .
// Array.prototype.map, .
var map = Array.prototype.map
? function(a, f) { return a.map(f); } // map()
: function(a,f) { //
var results = [];
for(var i = 0, len = a.length; i < len; i++) {
if (i in a) results[i] = f.call(null, a[i], i, a);
}
return results;
};
// , f
// . Array.prototype.reduce,
// .
var reduce = Array.prototype.reduce
? function(a, f, initial) { // reduce() .
if (arguments.length > 2)
return a.reduce(f, initial); // .
else return a.reduce(f); // .
}
: function(a, f, initial) { // ES5
var i = 0, len = a.length, accumulator;
// a
if (arguments.length > 2) accumulator = initial;
else { //
if (len == 0) throw TypeError();
while(i < len) {
if (i in a) {
accumulator = a[i++];
break;
}
else i++;
}
if (i == len) throw TypeError();
}
// f
while(i < len) {
if (i in a)
accumulator = f.call(undefined, accumulator, a[i], i, a);
i++;
}
return accumulator;
};

map() reduce()
:

8.8.
var
var
var
var
var
var

217

data = [1,1,3,5,5];
sum = function(x,y) { return x+y; };
square = function(x) { return x*x; };
mean = reduce(data, sum)/data.length;
deviations = map(data, function(x) {return x-mean;});
stddev = Math.sqrt(reduce(map(deviations, square), sum)/(data.length-1));

8.8.2.
, ,
. :
// ,
// f , f;
function not(f) {
return function() { //
var result = f.apply(this, arguments); // f
return !result; // .
};
}
var even = function(x) { // ,
return x % 2 === 0;
};
var odd = not(even); // ,
[1,1,3,5,5].every(odd); // => true:

not() ,
.
mapper(), .
,
, .
map(), ,
, :
// , , f
// .
// map(), .
function mapper(f) {
return function(a) { return map(a, f); };
}
var increment = function(x) { return x+1; };
var incrementer = mapper(increment);
incrementer([1,2,3]) // => [2,3,4]

, ,
, f g, ,
f(g()):
// , f(g(...)). h
// g, , g,
// f f. , f g,
// this, h.
function compose(f,g) {

218

8.

return function() {
// f call,
// , g apply,
// .
return f.call(this, g.apply(this, arguments));
};
}
var square = function(x) { return x*x; };
var sum = function(x,y) { return x+y; };
var squareofsum = compose(square, sum);
squareofsum(2,3) // => 25

partial() memoize(), ,
.

8.8.3.
bind() f (8.7.4) ,
f . ,
.
bind() , .. ,
bind(), ,
. :
// ( ),
// , .
// arguments .
function array(a, n) { return Array.prototype.slice.call(a, n || 0); }
//
function partialLeft(f /*, ...*/) {
var args = arguments; //
return function() { //
var a = array(args, 1); // 1 . .
a = a.concat(array(arguments)); // .
return f.apply(this, a); // f
};
}
//
function partialRight(f /*, ...*/) {
var args = arguments; //
return function() { //
var a = array(arguments); // . .
a = a.concat(array(args,1)); // ., 1.
return f.apply(this, a); // f
};
}
// .
// .
function partial(f /*, ... */) {
var args = arguments; //
return function() {
var a = array(args, 1); //

8.8.

219

var i=0, j=0;


// , undefined
//
for(; i < a.length; i++)
if (a[i] === undefined) a[i] = arguments[j++];
//
a = a.concat(array(arguments, j))
return f.apply(this, a);
};
}
// ,
var f = function(x,y,z) { return x * (y - z); };
//
partialLeft(f, 2)(3,4) // => -2: : 2 * (3 - 4)
partialRight(f, 2)(3,4) // => 6: : 3 * (4 - 2)
partial(f, undefined, 2)(3,4) // => -6: : 3 * (2 - 4)


. :
var increment = partialLeft(sum, 1);
var cuberoot = partialRight(Math.pow, 1/3);
String.prototype.first = partial(String.prototype.charAt, 0);
String.prototype.last = partial(String.prototype.substr, -1, 1);

,
. ,
not(), ,
:
var
var
var
var

not = partialLeft(compose, function(x) { return !x; });


even = function(x) { return x % 2 === 0; };
odd = not(even);
isNumber = not(isNaN)



:
var
var
var
var
var
var
var

data = [1,1,3,5,5]; //
sum = function(x,y) { return x+y; }; //
product = function(x,y) { return x*y; };
neg = partial(product, -1); //
square = partial(Math.pow, undefined, 2);
sqrt = partial(Math.pow, undefined, .5);
reciprocal = partial(Math.pow, undefined, -1);

// .
// ,
// Lisp!
var mean = product(reduce(data, sum), reciprocal(data.length));
var stddev = sqrt(product(reduce(map(data,
compose(square,
partial(sum, neg(mean)))),
sum),
reciprocal(sum(data.length,-1))));

220

8.

8.8.4.
8.4.1 ,
.
(memorization).
memoize() ,
:
// f. ,
// f .
function memoize(f) {
var cache = {}; // .
return function() {
// arguments
// .
var key = arguments.length + Array.prototype.join.call(arguments,",");
if (key in cache) return cache[key];
else return cache[key] = f.apply(this, arguments);
};
}

memoize()
,
( ) .
arguments
-. ,
. ,
;
.
, memoize():
// ,
// : http://en.wikipedia.org/wiki/Euclidean_algorithm
function gcd(a,b) { // a b
var t; //
if (a < b) t=b, b=a, a=t; // , a >= b
while(b != 0) t=b, b = a%b, a=t; //
return a;
}
var gcdmemo = memoize(gcd);
gcdmemo(85, 187) // => 17
// , ,
// , .
var factorial = memoize(function(n) {
return (n <= 1) ? 1 : n * factorial(n-1);
});
factorial(5) // => 120. 4, 3, 2 1.

9
9.

JavaScript- 6,
, .
,
. , ,
, , (
), .
. ,
Complex
. Complex
.
Complex ,
() .
JavaScript
. , , .
6.1.3 6.2.2.
,
. 9.1.
, ( )
,
. 4.6, 6.1.2 8.2.3.
9.2.
, -
, Java C++, ,
JavaScript . ,
,
JavaScript.
, Java
Script

222

9.

Java . 9.3
JavaScript.
JavaScript
. 9.4.
, 9.5
.
,
(duck-typing), ,
.
-
JavaScript
. 9.6
-
. 9.7 (
),
JavaScript. 9.8
,
ECMAScript5.

.
JavaScript.

9.1.
JavaScript ,
-. , -
. 6.1 inherit(),
, -.
- inherit()
, , Java
Script. ,
,
. 9.1 : , ,
, .
9.1. JavaScript
// range.js: , .
// , range.
function range(from, to) {
// inherit() , -,
// . -
// () range.
var r = inherit(range.methods);
// range.
// , .
r.from = from;
r.to = to;

9.2.

223

//
return r;
}
// -, , range.
range.methods = {
// true, x - range, false
// ,
// Date.
includes: function(x) { return this.from <= x && x <= this.to; },
// f .
// .
foreach: function(f) {
for(var x = Math.ceil(this.from); x <= this.to; x++) f(x);
},
//
toString: function() { return "(" + this.from + "..." + this.to + ")"; }
};
// range.
var r = range(1,3); // range
r.includes(2); // => true: 2
r.foreach(console.log); // 1 2 3
console.log(r); // (1...3)

9.1 ,
. range(),
range. , , , range.methods
range(). - . , , range() from to
range. ,
range. ,
, , , range.
methods, from to
this, ,
. this
.

9.2.
9.1 Ja
vaScript. ,
. ,
. 8.2.3,
new.
new ,
.

prototype . ,
, ,

224

9.

- , ,
. 9.2 , range,
9.1, ,
:
9.2. Range
// range2.js: , .
// -, Range.
// , .
// .
function Range(from, to) {
// range.
// , .
this.from = from;
this.to = to;
}
// Range .
// , "prototype".
Range.prototype = {
// true, x - range, false
// ,
// Date.
includes: function(x) { return this.from <= x && x <= this.to; },
// f .
// .
foreach: function(f) {
for(var x = Math.ceil(this.from); x <= this.to; x++) f(x);
},
//
toString: function() { return "(" + this.from + "..." + this.to + ")"; }
};
// range.
var r = new Range(1,3); // range
r.includes(2); // => true: 2
r.foreach(console.log); // 1 2 3
console.log(r); // (1...3)

9.1 9.2
. -, ,
range()
Range(). : -
,
.
.
, Range() ( )
new, range() .
9.1
( 8.2.1), 9.2 ( 8.2.3).
Range() new,
inherit() -

9.2.

225

.
this. Range()
.
.
,
. ,
, ,
, .
, new,

. ,
,
new.
9.1 9.2
-. range.
methods. , ,
. Range.prototype,
. Range()
Range.prototype Range.
, 9.1
9.2: range
.

9.2.1.
, -
: ,
-. -,
, :
prototype, -.
.
,
, .
, . ,
, Range() Range.

instanceof .
r, , Range,
:
r instanceof Range // true, r Range.prototype

instanceof , r
Range. ,
Range.prototype. , instanceof
.
instanceof .

226

9.

9.2.2. constructor
9.2 Range.prototype ,
.
-,
. JavaScript ,
prototype.
, ( , Func
tion.bind() ECMAScript5) prototype.
,
constructor. constructor :
var F
var p
var c
c ===

= function() {}; //
= F.prototype; //
= p.constructor; //
F //

.
-, .
, .
=> true: F.prototype.constructor === F

- constructor
, constructor,
. ,
constructor :
var o = new F(); // F
o.constructor === F // => true: constructor

-, ,
,
, .9.1.

Range()
prototype

constructor
includes: ...
foreach: ...
toString: ...

new Range(1,2)

new Range(3,4)

.9.1. -,

, .9.1
Range(). Range, 9.2,
Range.prototype .
- constructor.
Range, , constructor.
, :
Range.prototype = {
constructor: Range, //
includes: function(x) { return this.from <= x && x <= this.to; },
foreach: function(f) {
for(var x = Math.ceil(this.from); x <= this.to; x++) f(x);
},

9.3. Java

227

toString: function() { return "(" + this.from + "..." + this.to + ")"; }


};

,
-, constructor,
:
// Range.prototype,
//
// Range.prototype.constructor.
Range.prototype.includes = function(x) { return this.from<=x && x<=this.to; };
Range.prototype.foreach = function(f) {
for(var x = Math.ceil(this.from); x <= this.to; x++) f(x);
};
Range.prototype.toString = function() {
return "(" + this.from + "..." + this.to + ")";
};

9.3. Java
Java -
, , ,
, :

, ,
.

, ,
.

, , ,
.

, .
JavaScript, Java,
, JavaScript ,
. ,
. ,
. , ,
JavaScript.
JavaScript (.9.1),
:
-
, - () JavaScript
. , ,
( ,
).

228

9.

-
,
, ,
.

, ,
,
. , ,
.
JavaScript . , -,
. -,
- . -,
. ,
defineClass(). ( extend()
6.2 8.3):
//
function defineClass(constructor, // ,
methods, // :
statics) // :
{
if (methods) extend(constructor.prototype, methods);
if (statics) extend(constructor, statics);
return constructor;
}
// Range
var SimpleRange =
defineClass(function(f,t) { this.f = f; this.t = t; },
{
includes: function(x) { return this.f<=x && x <= this.t;},
toString: function() { return this.f + "..." + this.t; }
},
{ upto: function(t) { return new SimpleRange(0, t); } });

9.3 .
, , ,
Java.
defineClass(), .
9.3. Complex.js:
/*
* Complex.js:
* Complex, .
* , ,
* i -1.
*/
/*
* - r i
* .

9.3. Java

229

* :
* , .
*/
function Complex(real, imaginary) {
if (isNaN(real) || isNaN(imaginary)) // , - .
throw new TypeError(); // .
this.r = real; // .
this.i = imaginary; // .
}
/*
* - -.
* , ,
* . , JavaScript
* this .
*/
// that .
Complex.prototype.add = function(that) {
return new Complex(this.r + that.r, this.i + that.i);
};
// that .
Complex.prototype.mul = function(that) {
return new Complex(this.r * that.r - this.i * that.i,
this.r * that.i + this.i * that.r);
};
// .
// (0,0).
Complex.prototype.mag = function() {
return Math.sqrt(this.r*this.r + this.i*this.i);
};
// .
Complex.prototype.neg = function() { return new Complex(-this.r, -this.i); };
// Complex .
Complex.prototype.toString = function() {
return "{" + this.r + "," + this.i + "}";
};
// .
Complex.prototype.equals = function(that) {
return that != null && // , null
that.constructor === Complex && // Complex
this.r === that.r && this.i === that.i; // .
};
/*
* (, )
* . ,
* this: .
*/
// ,
// . ,

230

9.

// , .
// (ECMAScript5 )
Complex.ZERO = new Complex(0,0);
Complex.ONE = new Complex(1,0);
Complex.I = new Complex(0,1);
// ,
// toString, Complex TypeError.
Complex.parse = function(s) {
try { // ,
var m = Complex._format.exec(s); //
return new Complex(parseFloat(m[1]), parseFloat(m[2]));
} catch (x) { //
throw new TypeError(" '" + s + "' " +
" .");
}
};
// "" , Complex.parse().
// ,
// API .
Complex._format = /^\{([^,]+),([^}]+)\}$/;

Complex, 9.3,
, , ,
, :
var c = new Complex(2,3); //
var d = new Complex(c.i,c.r); // c
c.add(d).toString(); // => "{5,5}":
// ,
Complex.parse(c.toString()). // c ,
add(c.neg()). // ,
equals(Complex.ZERO) //

JavaScript
Java, Java ,
JavaScript. -,
Java ,
, Java
this. JavaScript ,
with (
):
Complex.prototype.toString = function() {
with(this) {
return "{" + r + "," + i + "}";
}
};

Java
final, , ,
private, ,
. JavaScript
, , (

9.4.

231

) ,
( ), 9.3
.
:
( 9.6.6), ECMAScript5 (9.8.2).

9.4.
, JavaScript,
:
, .
, JavaScript
-.
,
Complex 9.3:
// ,
// .
Complex.prototype.conj = function() { return new Complex(this.r, -this.i); };

- JavaScript
, ,
, , , ..
8.5. bind()
ECMAScript3, :
if (!Function.prototype.bind) {
Function.prototype.bind = function(o /*, */) {
// bind...
};
}

:
// f , ;
//
// , "" 3 :
// var n = 3;
// n.times(function(n) { console.log(n + " "); });
Number.prototype.times = function(f, context) {
var n = Number(this);
for(var i = 0; i < n; i++) f.call(context, i);
};
// ES5 String.trim(), .
// .
String.prototype.trim = String.prototype.trim || function() {
if (!this) return this; //
return this.replace(/^\s+|\s+$/g, ""); //
};
// . name (),
// . .

232

9.

// .
Function.prototype.getName = function() {
return this.name || this.toString().match(/function\s*([^(]*)\(/)[1];
};

Object.prototype,
. ,
, ECMAScript5,
. Object.pro
totype for/in.
9.8.1 Object.defineProperty(),
ECMAScript5, Object.prototype.
,
( -), . -
, , HTMLElement.prototype,
, HTML
.
Microsoft Internet Explorer,
.

9.5.
3 , JavaScript
: null, undefined, , , ,
. typeof (4.13.2) .

.
JavaScript (
JavaScript) class ( 6.8.2),
, classof() 6.4.
, ,
class Object,
classof() .

: instanceof, constructor -
. ,
9.5.4 (duck-typing)
,
(.. ), .

9.5.1. instanceof
instanceof 4.9.4.
, ,
-, . o in
stanceof c true, o c.prototype.
. o ,
, c.prototype, true.

9.5.

233

,
,
. instanceof , ,
, , .
,
-,
, isPrototypeOf(). ,
, r range,
9.1:
range.methods.isPrototypeOf(r); // range.methods - -.

instanceof isPrototypeOf() ,
.
.
JavaScript, -
.
,
-. ,
, , ,
, , instanceof
Array() .

9.5.2. constructor

constructor. ,
. :
function typeAndValue(x) {
if (x == null) return ""; // null undefined .
switch(x.constructor) {
case Number: return "Number: " + x; //
case String: return "String: '" + x + "'";
case Date: return "Date: " + x; //
case RegExp: return "Regexp: " + x;
case Complex: return "Complex: " + x; //
}
}

, ,
case, . typeof
class , .
, constructor,
, instanceof.
(,
),
. -:
Array Array
.

234

9.

, JavaScript , con
structor: , -
,
constructor . ,
( 9.1 9.2) ,
constructor.

9.5.3.
instanceof constructor

, , . ,
, , .
,
-
. Array Array
, . JavaScript
name
. , name ,
. ( 9.4,
Function getName().)
9.4 type(),
.
typeof. class,
. type() classof()
6.4 Function.getName() 9.4.
.
9.4. type()
/**
* :
* - o - null, "null", o - NaN, "nan".
* - typeof , "object", .
* ( ,
* .)
* - class o "Object",
* .
* - o constructor, ,
* .
* - "Object".
**/
function type(o) {
var t, c, n; // type, class, name
// null:
if (o === null) return "null";
// : NaN - , :
if (o !== o) return "nan";

9.5.

235

// typeof , "object".
// .
if ((t = typeof o) !== "object") return t;
// , "Object".
// .
if ((c = classof(o)) !== "Object") return c;
// ,
if (o.constructor && typeof o.constructor === "function" &&
(n = o.constructor.getName())) return n;
// ,
// "Object"
return "Object";
}
// .
function classof(o) {
return Object.prototype.toString.call(o).slice(8,-1);
};
// ( "") null - ,
//
Function.prototype.getName = function() {
if ("name" in this) return this.name;
return this.name = this.toString().match(/function\s*([^(]*)\(/)[1];
};

,
, ,
constructor: constructor. ,
. ,
, getName()
:
//
var Complex = function(x,y) { this.r = x; this.i = y; }
//
var Range = function Range(f,t) { this.from = f; this.to = t; }

9.5.4.
, ,
, , JavaScript.
, ?
?.
, Python Ruby,
(duck-typing, )
( (James Whitcomb Riley)):
, , , , ,
, .

JavaScript
: , Duck,

236

9.

Duck, -
Duck.
Range 9.2.
. ,
Range() , ,
. includes() <=,
.
, includes()
,
:
var lowercase = new Range("a", "z");
var thisYear = new Range(new Date(2009, 0, 1), new Date(2010, 0, 1));

foreach() Range ,
Math.ceil() ++,
.
, ,
7.11. ,
Array: ,
length .
, length ,
, , , (
) .
, length
: length
, length ,
. , ,
. , ,
,
, .
, ,
<
length.
.
triathlon() ,
TriAthlete. ,
, , walk(), swim() bike().
, Range ,
< ++ compareTo() succ()
.
: ,
,
. ,
.
. ,
,
.
.

9.5.

237

9.5 quacks() (
implements (), implements ),
. quacks()
( ) ,
. ,
, .
, ,
. , ,
,
, -.
9.5.
// true, o , .
function quacks(o /*, ... */) {
for(var i=1; i<arguments.length; i++) { // o
var arg = arguments[i];
switch(typeof arg) { // arg - :
case 'string': // :
if (typeof o[arg] !== "function") return false;
continue;
case 'function': // : -
// ,
arg = arg.prototype;
// case
case 'object': // : .
for(var m in arg) { //
if (typeof arg[m]!=="function") continue; // ,
//
if (typeof o[m] !== "function") return false;
}
}
}
// , , o ,
return true;
}

, quacks(),
. -,
.
, , ,
. .
,
, ,

. , quacks(),
, . ,
quacks(o, Array), , o
Array. ,
for/in quacks() . (
, ECMAScript5
Object.getOwnProperty Names().)

238

9.

9.6. -
JavaScript

JavaScript: -, , instanceof ..
( )
JavaScript .
, ,
.

9.6.1. :
,
.

, ,
. JavaScript
, .
, .
9.6 Set.
, JavaScript,
.
, , Set
,
.
9.6. Set.js:
function Set() { //
this.values = {}; //
this.n = 0; //
this.add.apply(this, arguments); // ,
} //
// .
Set.prototype.add = function() {
for(var i = 0; i < arguments.length; i++) { //
var val = arguments[i]; //
var str = Set._v2s(val); //
if (!this.values.hasOwnProperty(str)) { // .
this.values[str] = val; // .
this.n++; //
}
}
return this; //
};
// .
Set.prototype.remove = function() {
for(var i = 0; i < arguments.length; i++) { //
var str = Set._v2s(arguments[i]); //

9.6. - JavaScript

239

if (this.values.hasOwnProperty(str)) { // .
delete this.values[str]; //
this.n--; //
}
}
return this; //
};
// true, value; false.
Set.prototype.contains = function(value) {
return this.values.hasOwnProperty(Set._v2s(value));
};
// .
Set.prototype.size = function() { return this.n; };
// f .
Set.prototype.foreach = function(f, context) {
for(var s in this.values) //
if (this.values.hasOwnProperty(s)) // .
f.call(context, this.values[s]); // f
};
// . JavaScript
// .
Set._v2s = function(val) {
switch(val) {
case undefined: return 'u'; //
case null: return 'n'; // .
case true: return 't';
case false: return 'f';
default: switch(typeof val) {
case 'number': return '#' + val; // #.
case 'string': return '"' + val; // ".
default: return '@' + objectId(val); // - @
}
}
// .
// ,
// . o .
// ES5 .
function objectId(o) {
var prop = "|**objectid**|"; // .
if (!o.hasOwnProperty(prop)) //
o[prop] = Set._v2s.next++; // . .
return o[prop]; //
}
};
Set._v2s.next = 100; // .

9.6.2. : -
,
, ( ) .

240

9.

C -
enum. ECMAScript5 enum (
) , , - JavaScript
-. 9.7
, - JavaScript.
, inherit() 6.1.
9.7 enumeration().
: enumeration.
:
. , :
// Coin :
// Coin.Penny, Coin.Nickel ..
var Coin = enumeration({Penny: 1, Nickel:5, Dime:10, Quarter:25});
var c = Coin.Dime; //
c instanceof Coin // => true: instanceof
c.constructor == Coin // => true: constructor
Coin.Quarter + 3*Coin.Nickel // => 40:
Coin.Dime == 10 // => true:
Coin.Dime > Coin.Nickel // => true:
String(Coin.Dime) + ":" + Coin.Dime // => "Dime:10": .

, ,
JavaScript ,
, C++ Java.
9.7. - JavaScript
// -.
// . -,
// . , ,
// : .
// , ,
// values foreach()
function enumeration(namesToValues) {
// ,
// .
var enumeration = function() { throw " " +
" Enumeration"; };
// this.
var proto = enumeration.prototype = {
constructor: enumeration, //
toString: function() { return this.name; }, //
valueOf: function() { return this.value; }, //
toJSON: function() { return this.name; } //
};

enumeration.values = []; // -
// .
for(name in namesToValues) { //
var e = inherit(proto); //
e.name = name; //
e.value = namesToValues[name]; //

9.6. - JavaScript

241

enumeration[name] = e; //
enumeration.values.push(e); // values
}
//
enumeration.foreach = function(f,c) {
for(var i = 0; i < this.values.length; i++) f.call(c,this.values[i]);
};
// ,
return enumeration;
}

-
.
9.8 enumeration() ,
.1
9.8. -
//
function Card(suit, rank) {
this.suit = suit; //
this.rank = rank; //
}
// -
Card.Suit = enumeration({Clubs: 1, Diamonds: 2, Hearts:3, Spades:4});
Card.Rank = enumeration({Two: 2, Three: 3, Four: 4, Five: 5, Six: 6,
Seven: 7, Eight: 8, Nine: 9, Ten: 10,
Jack: 11, Queen: 12, King: 13, Ace: 14});
//
Card.prototype.toString = function() {
return this.rank.toString() + " " + this.suit.toString();
};
//
Card.prototype.compareTo = function(that) {
if (this.rank < that.rank) return -1;
if (this.rank > that.rank) return 1;
return 0;
};
//
Card.orderByRank = function(a,b) { return a.compareTo(b); };
//
Card.orderBySuit = function(a,b) {
if (a.suit < b.suit) return -1;
if (a.suit > b.suit) return 1;
if (a.rank < b.rank) return -1;
if (a.rank > b.rank) return 1;

Java, (Joshua
Bloch) : http://jcp.org/aboutJava/communityprocess/jsr/tiger/enum.
html.

242

9.

return 0;
};
//
function Deck() {
var cards = this.cards = []; // -
Card.Suit.foreach(function(s) { //
Card.Rank.foreach(function(r) {
cards.push(new Card(s,r));
});
});
}
// :
Deck.prototype.shuffle = function() {
// :
//
var deck = this.cards, len = deck.length;
for(var i = len-1; i > 0; i--) {
var r = Math.floor(Math.random()*(i+1)), temp; //
temp = deck[i], deck[i] = deck[r], deck[r] = temp; //
}
return this;
};
// :
Deck.prototype.deal = function(n) {
if (this.cards.length < n) throw " ";
return this.cards.splice(this.cards.length-n, n);
};
// ,
var deck = (new Deck()).shuffle();
var hand = deck.deal(13).sort(Card.orderBySuit);

9.6.3.
3.8.3 6.10 ,
,
JavaScript .
, ,
, ,
.
toString().
, . Java
Script , ,
, , +,
. ,
Object.prototype
[object Object]. toString()
,
.
, toString(),

9.6. - JavaScript

243

. Range Complex, 9.2


9.3, toString(), -
, 9.7.
toString() Set 9.6.
toString() toLocaleString():
.
toLocaleString(), toString().
toLocale
String(), .
toString()
, toLocaleString(),
toLocaleString() .
Set.
valueOf().
. valueOf() ,
, ,
( +) .
-
. - 9.7 ,
valueOf() .
toJSON() JSON.stringi
fy(). JSON
,
.
,
. JSON.stringify() Range
Complex, , {"from":1, "to":3} {"r":1, "i":-1}.
JSON.parse(),
, Range Complex,
Range Complex.
, Range Comp
lex,
toJSON(), .
toJSON(), JSON.stringify()
, toJSON() (
), . , Date
toJSON(), .
- 9.7 : toJSON()
, toString().
JSON ,
toJSON(), Set .
Set, 9.6, .
,
valueOf(),
toString(), toLocaleString() toJSON(). ,
. , Set.prototype
extend() (6.2):

244

9.

// - Set.
extend(Set.prototype, {
//
toString: function() {
var s = "{", i = 0;
this.foreach(function(v) { s += ((i++ > 0)?", ":"") + v; });
return s + "}";
},
// , toString, toLocaleString
//
toLocaleString : function() {
var s = "{", i = 0;
this.foreach(function(v) {
if (i++ > 0) s += ", ";
if (v == null) s += v; // null undefined
else s += v.toLocaleString(); //
});
return s + "}";
},
//
toArray: function() {
var a = [];
this.foreach(function(v) { a.push(v); });
return a;
}
});
// JSON .
Set.prototype.toJSON = Set.prototype.toArray;

9.6.4.
JavaScript ,
. , , ,
, ,
.1

(, < >).

, ,
.
Java
, JavaScript.
,
equals().
true, ,
. , ,
.
constructor, ,
1

- . .
. .

9.6. - JavaScript

245

, , ,
. Complex 9.3
equals(),
Range:
// Range constructor. .
Range.prototype.constructor = Range;
// Range ,
// . , .
Range.prototype.equals = function(that) {
if (that == null) return false; // null undefined
if (that.constructor !== Range) return false; //
// true, .
return this.from == that.from && this.to == that.to;
}

equals() Set .
values
:
Set.prototype.equals = function(that) {
//
if (this === that) return true;
// that , this.
// Set instanceof.
// ,
// .
// ,
// this.constructor == that.constructor.
// , instanceof
// null undefined
if (!(that instanceof Set)) return false;
// ,
if (this.size() != that.size()) return false;
// , this that.
// foreach, .
try {
this.foreach(function(v) { if (!that.contains(v)) throw false; });
return true; // : .
} catch (x) {
if (x === false) return false; // this that.
throw x; // : .
}
};

,
. , ,
. , Range
, . -

, (,

246

9.

). , Set
- .
, <
<=, valueOf() ,
, . -,
enumeration() 9.7, valueOf()
.
valueOf().
, ( ,
, Java)
compareTo().
compareTo()
, . this , ,
, compareTo()
. this , , ,
. ,
.
,
:

a < b

a.compareTo(b) < 0

a <= b

a.compareTo(b) <= 0

a > b

a.compareTo(b) > 0

a >= b

a.compareTo(b) >= 0

a == b

a.compareTo(b) == 0

a != b

a.compareTo(b) != 0

Card 9.8 compareTo(),


Range,
:
Range.prototype.compareTo = function(that) {
return this.from - that.from;
};

, , ,
,
Range. Card.Rank 9.8
valueOf(), compa
reTo() Card.
equals(), ,
false, ,
. compareTo() ,
,
, compareTo()
.

9.6. - JavaScript

247

, compareTo() Range, ,
0, .
, compareTo()
, .
, equals(),
.
,
equals() compareTo() .
compareTo() Range.
equals()
:
//
// , . ,
// , Range.
// 0, this.equals(that) true.
Range.prototype.compareTo = function(that) {
if (!(that instanceof Range))
throw new Error(" Range " + that);
var diff = this.from - that.from; //
if (diff == 0) diff = this.to - that.to; // ,
return diff;
};

,
, .
Array.sort()
,
, compareTo(). compareTo(),
, Range,
:
ranges.sort(function(a,b) { return a.compareTo(b); });

,
,
compareTo(). ,
, :
Range.byLowerBound = function(a,b) { return a.compareTo(b); };


:
ranges.sort(Range.byLowerBound);

.
, Card ,
, .

9.6.5.
JavaScript ,
.

248

9.


. Set, ,
toArray()
toJSON().

. Array, ,
, Array.prototype ,
, .
JavaScript -
,
.
JavaScript -
,
.
Array:
. 9.9
toString() equals(), ,
Range, Complex Card. Range equals(),
equals(), :
Range.prototype.equals = generic.equals;

, generic.equals()
,
equals().
, ,
Set (9.6).
9.9. ,
var generic = {
// , -, ,
// , .
toString: function() {
var s = '[';
// ,
// . ,
// name .
if (this.constructor && this.constructor.name)
s += this.constructor.name + ": ";
// ,
var n = 0;
for(var name in this) {
if (!this.hasOwnProperty(name)) continue; // .
var value = this[name];
if (typeof value === "function") continue; //
if (n++) s += ", ";
s += name + '=' + value;
}
return s + ']';
},

9.6. - JavaScript

249

// , this
// that. ,
// ===.
// , Set.
equals: function(that) {
if (that == null) return false;
if (this.constructor !== that.constructor) return false;
for(var name in this) {
if (name === "|**objectid**|") continue; // . .
if (!this.hasOwnProperty(name)) continue; // . .
if (this[name] !== that[name]) return false; //
}
return true; // , .
}
};

9.6.6.
-
, ,

. , Java,
(private)
,
.
(
), , ,
. (

), .
9.10,
Range. from to,
,
from to, . from() to()
, Range.
Range , ,

from() to().
9.10. Range
function Range(from, to) {
// . ,
// . .
this.from = function() { return from; };
this.to = function() { return to; };
}
// :
// , .
Range.prototype = {
constructor: Range,

250

9.

includes: function(x) { return this.from() <= x && x <= this.to(); },


foreach: function(f) {
for(var x=Math.ceil(this.from()), max=this.to(); x <= max; x++) f(x);
},
toString: function() { return "(" + this.from() + "..." + this.to() + ")"; }
};

Range ,
.
:
Range .
ECMAScript5 (9.8.3),
from to -
Range :
var r = new Range(1,5); // ""
r.from = function() { return 0; }; //

, .
, ,
,
.

9.6.7.

. ,
Complex (
) .
Set, ,
.


.
Set:
function Set() {
this.values = {}; //
this.n = 0; //
// , ,
// .
//
if (arguments.length == 1 && isArrayLike(arguments[0]))
this.add.apply(this, arguments[0]);
else if (arguments.length > 0)
this.add.apply(this, arguments);
}

Set()

. , :

9.6. - JavaScript

251

,
. ( ,
add().)

, ,
.
. ,
, .
,
. ,
Complex, :
Complex.polar = function(r, theta) {
return new Complex(r*Math.cos(theta), r*Math.sin(theta));
};

Set
:
Set.fromArray = function(a) {
s = new Set(); //
s.add.apply(s, a); // add
return s; //
};

,
,
. ,
.
. JavaScript , -, ,
,
. ,
:
// Set.
function SetFromArray(a) {
// Set() ,
// .
Set.apply(this, a);
}
// , SetFromArray Set
SetFromArray.prototype = Set.prototype;
var s = new SetFromArray([1,2,3]);
s instanceof Set // => true

ECMAScript 5 bind(),
(8.7.4).

252

9.

9.7.
- B ,
, A. A ,
B . B
A. B ,
A .
B A, B
A:
. B()
A() .
. ,
,
. ,
.
.
JavaScript
-. B A, B.prototype
A.prototype. B
B.prototype,
A.prototype.
, , ,
, .
Set 9.6,
, ,
,
, ,
. ,
Set. ,

, ,
.

9.7.1.
JavaScript ( ) -
. O B, B
A, O A.
- B
- A, ,
inherit() (6.1):
B.prototype = inherit(A.prototype); //
B.prototype.constructor = B; // . constructor

JavaScript.
- ,
Object.prototype, , Object,
. defineClass()

9.7.

253

(9.3), defineSubclass()
Function.prototype.extend(), 9.11.
9.11.
//
function defineSubclass(superclass, //
constructor, //
methods, // .:
statics) // : -
{
// -
constructor.prototype = inherit(superclass.prototype);
constructor.prototype.constructor = constructor;
// methods statics,
if (methods) extend(constructor.prototype, methods);
if (statics) extend(constructor, statics);
//
return constructor;
}
//
Function.prototype.extend = function(constructor, methods, statics) {
return defineSubclass(this, constructor, methods, statics);
};

9.12 , ,
defineSubclass(). SingletonSet
Set. SingletonSet ,
.
9.12. SingletonSet:
// -
function SingletonSet(member) {
this.member = member; //
}
// -, - Set.
SingletonSet.prototype = inherit(Set.prototype);
// .
// Set.prototype.
extend(SingletonSet.prototype, {
// constructor
constructor: SingletonSet,
// : add() remove()
//
add: function() { throw " "; },
remove: function() { throw " "; },
// SingletonSet , 1
size: function() { return 1; },
// .
foreach: function(f, context) { f.call(context, this.member); },
// contains() :
//

254

9.

contains: function(x) { return x === this.member; }


});

SingletonSet ,
. Set,
, toString(), toArray() equals().

. equals() Set ( 9.6.4),
, Set, size()
foreach(), Set, size() con
tains(). SingletonSet Set,
equals()
. ,
, ,
SingletonSet equals():
SingletonSet.prototype.equals = function(that) {
return that instanceof Set && that.size()==1 && that.contains(this.member);
};

, SingletonSet
Set: Set. Set.prototype
, Set
SingletonSet (, SingletonSet
).

9.7.2.
SingletonSet
,
.
,
.
.
9.13 .
NonNullSet Set: ,
null undefined.
, NonNullSet add()
null undefined.
add()
. ,
NonNullSet() :
( ,
),
.
9.13.
/*
* NonNullSet - Set,
* null undefined.
*/

9.7.

255

function NonNullSet() {
// .
//
// , .
Set.apply(this, arguments);
}
// NonNullSet Set:
NonNullSet.prototype = inherit(Set.prototype);
NonNullSet.prototype.constructor = NonNullSet;
// null undefined,
// add()
NonNullSet.prototype.add = function() {
// null undefined
for(var i = 0; i < arguments.length; i++)
if (arguments[i] == null)
throw new Error(" null undefined NonNullSet");
// ,
return Set.prototype.add.apply(this, arguments);
};


: ,
- . (
enumeration() 9.7), Set.
,
: -,
add(). filtered
SetSubclass() , :
// ,
var StringSet = filteredSetSubclass(Set,
function(x) {return typeof x==="string";});
// , null,
// undefined
var MySet = filteredSetSubclass(NonNullSet,
function(x) {return typeof x !== "function";});

9.14.
,
, NonNullSet.
9.14.
/*
* Set
* add() , .
*/
function filteredSetSubclass(superclass, filter) {
var constructor = function() { //
superclass.apply(this, arguments); //
};

256

9.

var proto = constructor.prototype = inherit(superclass.prototype);


proto.constructor = constructor;
proto.add = function() {
//
for(var i = 0; i < arguments.length; i++) {
var v = arguments[i];
if (!filter(v)) throw(" " + v + " ");
}
// add
superclass.prototype.add.apply(this, arguments);
};
return constructor;
}

9.14 , .
, , ,
superclass
.
,
, .
,
. , -
NonNullSet Function.prototype.extend()
(9.11), :
var NonNullSet = (function() { //
var superclass = Set; // .
return superclass.extend(
function() { superclass.apply(this, arguments); }, //
{ //
add: function() {
// null undefined
for(var i = 0; i < arguments.length; i++)
if (arguments[i] == null)
throw new Error(" null undefined");
// ,
return superclass.prototype.add.apply(this, arguments);
}
});
}());

,
JavaScript.
,
, Java C++.

9.7.3.
,
,
,

9.7.

257

, -
.
- .
. -

.1
,

. 9.15 , .
9.15.
/*
* FilteredSet
* add().
* .
*/
var FilteredSet = Set.extend(
function FilteredSet(set, filter) { //
this.set = set;
this.filter = filter;
},
{ //
add: function() {
// ,
if (this.filter) {
for(var i = 0; i < arguments.length; i++) {
var v = arguments[i];
if (!this.filter(v))
throw new Error("FilteredSet: " + v +
" ");
}
}
// add() this.set.add()
this.set.add.apply(this.set, arguments);
return this;
},
//
// this.set .
remove: function() {
this.set.remove.apply(this.set, arguments);
return this;
},
contains: function(v) { return this.set.contains(v); },
size: function() { return this.set.size(); },
foreach: function(f,c) { this.set.foreach(f,c); }
});

. . . - .
. Java. .

258

9.


, FilteredSet.

. , NonNullSet,
, :
var s = new FilteredSet(new Set(), function(x) { return x !== null; });

:
var t = new FilteredSet(s, { function(x} { return !(x instanceof Set); });

9.7.4.

. Set.
, instanceof Set
Set, toString() equals().
, , ,

, Set.
SingletonSet (9.12)
Set,
,
. SingletonSet Set,
. SingletonSet
Set, .
- ,
JavaScript ,
. , AbstractSet,
, toString(),
, foreach(). Set,
SingletonSet FilteredSet AbstractSet.
FilteredSet SingletonSet .
9.16
. AbstractSet
, contains(). , ,
.
AbstractEnumerableSet, AbstractSet.
size() and foreach()
(toString(), toArray(), equals() ..). AbstractEnumerableSet
add() remove() ,
. SingletonSet .
, AbstractWritableSet, Abst
ractEnumerableSet.
add() remove() , union() inter
section(), . AbstractWritableSet
Set FilteredSet.
,
ArraySet.

9.7.

259

9.16 , .
,
Function.prototype.extend().
9.16.
// ,
//
function abstractmethod() { throw new Error(" "); }
/*
* AbstractSet , contains().
*/
function AbstractSet() {
throw new Error(" ");
}
AbstractSet.prototype.contains = abstractmethod;
/*
* NotSet - AbstractSet.
* ,
* .
* , ,
* , .
* , , - .
* ,
* Function.prototype.extend(), .
*/
var NotSet = AbstractSet.extend(
function NotSet(set) { this.set = set; },
{
contains: function(x) { return !this.set.contains(x); },
toString: function(x) { return "~" + this.set.toString(); },
equals: function(that) {
return that instanceof NotSet && this.set.equals(that.set);
}
}
);
/*
* AbstractEnumerableSet - AbstractSet.
* size() foreach()
* isEmpty(), toArray(), to[Locale]String() equals().
* , contains(), size() foreach(),
* .
*/
var AbstractEnumerableSet = AbstractSet.extend(
function() {
throw new Error(" ");
},
{
size: abstractmethod,
foreach: abstractmethod,
isEmpty: function() { return this.size() == 0; },
toString: function() {

260

9.

var s = "{", i = 0;
this.foreach(function(v) {
if (i++ > 0) s += ", ";
s += v;
});
return s + "}";
},
toLocaleString : function() {
var s = "{", i = 0;
this.foreach(function(v) {
if (i++ > 0) s += ", ";
if (v == null) s += v; // null undefined
else s += v.toLocaleString(); //
});
return s + "}";
},
toArray: function() {
var a = [];
this.foreach(function(v) { a.push(v); });
return a;
},
equals: function(that) {
if (!(that instanceof AbstractEnumerableSet)) return false;
// that ,
if (this.size() != that.size()) return false;
// this that.
try {
this.foreach(function(v){
if (!that.contains(v)) throw false;}
);
return true; // : .
} catch (x) {
if (x === false) return false; //
throw x; // .
}
}
});
/*
* SingletonSet - AbstractEnumerableSet.
* , .
*/
var SingletonSet = AbstractEnumerableSet.extend(
function SingletonSet(member) { this.member = member; },
{
contains: function(x) { return x === this.member; },
size: function() { return 1; },
foreach: function(f,ctx) { f.call(ctx, this.member); }
}
);
/*
* AbstractWritableSet - AbstractEnumerableSet.
* add() remove()
* union(), intersection() difference().

9.7.
*/
var AbstractWritableSet = AbstractEnumerableSet.extend(
function() {
throw new Error(" ");
},
{
add: abstractmethod,
remove: abstractmethod,
union: function(that) {
var self = this;
that.foreach(function(v) { self.add(v); });
return this;
},
intersection: function(that) {
var self = this;
this.foreach(function(v){ if(!that.contains(v)) self.remove(v);});
return this;
},
difference: function(that) {
var self = this;
that.foreach(function(v) { self.remove(v); });
return this;
}
});
/*
* ArraySet - AbstractWritableSet.
*
* contains(). contains()
* O(n) O(1),
* .
* , Array
* indexOf() forEach(), ES5.
*/
var ArraySet = AbstractWritableSet.extend(
function ArraySet() {
this.values = [];
this.add.apply(this, arguments);
},
{
contains: function(v) { return this.values.indexOf(v) != -1; },
size: function() { return this.values.length; },
foreach: function(f,c) { this.values.forEach(f, c); },
add: function() {
for(var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (!this.contains(arg)) this.values.push(arg);
}
return this;
},
remove: function() {
for(var i = 0; i < arguments.length; i++) {
var p = this.values.indexOf(arguments[i]);
if (p == -1) continue;

261

262

9.

this.values.splice(p, 1);
}
return this;
}
}
);

9.8. ECMAScript5
ECMAScript 5 ,
( ,
, ) .
6.6, 6.7 6.8.3
. ,
ECMAScript5 .

9.8.1.
Set, 9.6, ,
: object id
, . -

for/in, . ECMAScript5
, . 9.17
, Object.defineProperty(),
,
.
9.17.
//
//
(function() {
// objectId
// .
// . ,
// . ,
// .
Object.defineProperty(Object.prototype, "objectId", {
get: idGetter, //
enumerable: false, //
configurable: false //
});
// ,
// objectId
function idGetter() { // , id
if (!(idprop in this)) { // id
if (!Object.isExtensible(this)) //
throw Error(" id ");
Object.defineProperty(this, idprop, { // .
value: nextid++, //

263

9.8. ECMAScript5
writable: false, //
enumerable: false, //
configurable: false //
});
}
return this[idprop]; //
};
// idGetter()
//
var idprop = "|**objectId**|"; // ,
//
var nextid = 1; // id
}()); // -,

9.8.2.
, ECMAScript5
,
,
. 9.18 Range,
, Object.defineProperties() Object.
create(). , Object.defineProperties()
- ,
, .
:
,
. , 9.18
new -
.
9.18. ,

// 'new':
// ,
function Range(from,to) {
// from to, .
var props = {
from: {value:from, enumerable:true,writable:false,configurable:false},
to: {value:to, enumerable:true, writable:false, configurable:false}
};
if (this instanceof Range) //
Object.defineProperties(this, props); //
else //
return Object.create(Range.prototype, //
props); //
}





Range

// Range.prototype ,
// . enumerable,
// writable configurable, false.

264

9.

Object.defineProperties(Range.prototype, {
includes: {
value: function(x) { return this.from <= x && x <= this.to; }
},
foreach: {
value: function(f) {
for(var x = Math.ceil(this.from); x <= this.to; x++) f(x);
}
},
toString: {
value: function() { return "(" + this.from + "..." + this.to + ")"; }
}
});

9.18
Object.defineProperties() Object.create().
,
.
,
, .
9.19.
9.19.
// ( ) o
// .
function freezeProps(o) {
var props = (arguments.length == 1) // ,
? Object.getOwnPropertyNames(o) // ,
: Array.prototype.splice.call(arguments, 1); //
props.forEach(function(n) { //
//
//
if (!Object.getOwnPropertyDescriptor(o,n).configurable) return;
Object.defineProperty(o, n, { writable: false, configurable: false });
});
return o; // o
}
// ( ) o,
// .
function hideProps(o) {
var props = (arguments.length == 1) // ,
? Object.getOwnPropertyNames(o) // ,
: Array.prototype.splice.call(arguments, 1); //
props.forEach(function(n) { // for/in
//
if (!Object.getOwnPropertyDescriptor(o,n).configurable) return;
Object.defineProperty(o, n, { enumerable: false });
});
return o;
}

Object.defineProperty() Object.defineProperties()
,

9.8. ECMAScript5

265

.
false.
. , hideProps()
enumerable,
.

ECMAScript5,
. 9.20
Range, .
9.20.
function Range(from, to) { // Range
this.from = from;
this.to = to;
freezeProps(this); //
}
Range.prototype = hideProps({ //
constructor: Range,
includes: function(x) { return this.from <= x && x <= this.to; },
foreach: function(f) {for(var x=Math.ceil(this.from);x<=this.to;x++) f(x);},
toString: function() { return "(" + this.from + "..." + this.to + ")"; }
});

9.8.3.
9.6.6 9.10 ,
- ,
. ,
ECMAScript 3
. ECMAScript5
,
. 9.21.
9.21. Range
// Range ,
// , from <= to.
function Range(from, to) {
//
if (from > to) throw new Error("Range: from <= to");
// ,
function getFrom() { return from; }
function getTo() { return to; }
function setFrom(f) { // from > to
if (f <= to) from = f;
else throw new Error("Range: from <= to");
}
function setTo(t) { // to < from
if (t >= from) to = t;
else throw new Error("Range: to >= from");
}

266

9.

// ,
Object.defineProperties(this, {
from: {get:getFrom, set:setFrom, enumerable:true, configurable:false},
to: { get: getTo, set: setTo, enumerable:true, configurable:false }
});
}
// - , .
// from to ,
// .
Range.prototype = hideProps({
constructor: Range,
includes: function(x) { return this.from <= x && x <= this.to; },
foreach: function(f) {for(var x=Math.ceil(this.from);x<=this.to;x++) f(x);},
toString: function() { return "(" + this.from + "..." + this.to + ")"; }
});

9.8.4.
JavaScript.
ECMAScript 5
. Object.preventExtensions() (
6.8.3) . Object.
seal() : ,
,
. ( -
- ,
.)
Object.prototype, :
Object.seal(Object.prototype);

JavaScript
:
var original_sort_method = Array.prototype.sort;
Array.prototype.sort = function() {
var start = new Date();
original_sort_method.apply(this, arguments);
var end = new Date();
console.log(" " + (end - start) +
" .");
};

,
.
freezeProps(), .
Object.freeze(),
, Object.seal(),
.
, , ,
. o

9.8. ECMAScript5

267

p, , o.p
o.
, ,
Object.defineProperty(), Object.defineProperties()
Object.create(), . , ,
,
.
,
. enume
ration() 9.7.
- - values .
,
,
.
enumeration() :
Object.freeze(enumeration.values);
Object.freeze(enumeration);

, Object.freeze()
objectId,
9.17. ,
objectId (
) , .

9.8.5. ECMAScript5
9.22
ECMAScript5. stringSet,
AbstractWritableSet 9.16.
Object.create() -
, ,
. ,
.
null
Object.create() , .
, ,
, hasOwnProperty() in.
9.22. StringSet:
ECMAScript5
function StringSet() {
this.set = Object.create(null); //
this.n = 0;
this.add.apply(this, arguments);
}
// , Object.create
// .

268

9.

// writable,
// enumerable configurable, false.
// .
StringSet.prototype = Object.create(AbstractWritableSet.prototype, {
constructor: { value: StringSet },
contains: { value: function(x) { return x in this.set; } },
size: { value: function(x) { return this.n; } },
foreach: { value: function(f,c) { Object.keys(this.set).forEach(f,c); } },
add: {
value: function() {
for(var i = 0; i < arguments.length; i++) {
if (!(arguments[i] in this.set)) {
this.set[arguments[i]] = true;
this.n++;
}
}
return this;
}
},
remove: {
value: function() {
for(var i = 0; i < arguments.length; i++) {
if (arguments[i] in this.set) {
delete this.set[arguments[i]];
this.n--;
}
}
return this;
}
}
});

9.8.6.
6.7 ,
ECMAScript5, ,
. ,
ECMAScript5, ,
, ECMAScript5. 9.23
Object.prototype properties() (,
). , , ,

( ).
( ,
)
(
hideProps() freezeProps(), ).
ECMAScript5,
,
.

9.8. ECMAScript5

269

9.23. ECMAScript5
/*
* properties() Object.prototype, ,
* ,
* ( , ).
* :
* toString(), descriptors(), hide() show().
*/
(function namespace() { //
//
function properties() {
var names; //
if (arguments.length == 0) // this
names = Object.getOwnPropertyNames(this);
else if (arguments.length == 1 && Array.isArray(arguments[0]))
names = arguments[0]; //
else //
names = Array.prototype.splice.call(arguments, 0);
// Properties,
return new Properties(this, names);
}
// , Object.prototype.
// , .
Object.defineProperty(Object.prototype, "properties", {
value: properties,
enumerable: false, writable: true, configurable: true
});
// - properties().
// Properties .
function Properties(o, names) {
this.o = o; // ,
this.names = names; //
}
// , this
Properties.prototype.hide = function() {
var o = this.o, hidden = { enumerable: false };
this.names.forEach(function(n) {
if (o.hasOwnProperty(n))
Object.defineProperty(o, n, hidden);
});
return this;
};
//
Properties.prototype.freeze = function() {
var o = this.o, frozen = { writable: false, configurable: false };
this.names.forEach(function(n) {
if (o.hasOwnProperty(n))
Object.defineProperty(o, n, frozen);
});

270

9.

return this;
};
// , .
// :
// Object.defineProperties(dest, src.properties().descriptors());
Properties.prototype.descriptors = function() {
var o = this.o, desc = {};
this.names.forEach(function(n) {
if (!o.hasOwnProperty(n)) return;
desc[n] = Object.getOwnPropertyDescriptor(o,n);
});
return desc;
};
// , ,
// . "permanent"
// , "readonly" - ,
// , "hidden" - .
// ,
// .
Properties.prototype.toString = function() {
var o = this.o; //
var lines = this.names.map(nameToString);
return "{\n " + lines.join(",\n ") + "\n}";
function nameToString(n) {
var s = "", desc = Object.getOwnPropertyDescriptor(o, n);
if (!desc) return "nonexistent " + n + ": undefined";
if (!desc.configurable) s += "permanent ";
if ((desc.get && !desc.set) || !desc.writable) s += "readonly ";
if (!desc.enumerable) s += "hidden ";
if (desc.get || desc.set) s += "accessor " + n
else s += n + ": " + ((typeof desc.value==="function")?"function"
:desc.value);
return s;
}
};
// , -,
// , , , .
Properties.prototype.properties().hide();
}()); // .

9.9.


.
.
JavaScript.
, ,
.
JavaScript

9.9.

271

, . JavaScript
- (,
imports exports,
),
JavaScript
.
JavaScript
. , Dojo Google Closure
provide() require() .
CommonJS JavaScript (http://
commonjs.org) , ,
require().
,
, .
,
, , .
.
,
,
, ,
, .

,
( ) .
,

.
. , JavaScript
- :
, , .

9.9.1.

, .
,
(
). Set 9.6.
- Set.
, Set.prototype,
.
_v2s(),
Set.
9.16.
.
, ( )
.

272

9.

,
:
var sets = {};

sets ,
:
sets.SingletonSet = sets.AbstractEnumerableSet.extend(...);

,
,
:
var s = new sets.SingletonSet(1);

,
, ,
. ,
, , .


. , Set
sets, , :
var Set = sets.Set; // Set
var s = new Set(1,2,3); // sets.

.

, collections.sets,
:
var collections; // ( )
if (!collections) //
collections = {}; //
collections.sets = {} // sets.
// collections.sets
collections.sets.AbstractSet = function() { ... }



. , Google Closure
Set goog.structs.
,
,
. - davidflanagan.com,
com.davidflana
gan.collections.sets.

. ,
,
:
var sets = com.davidflanagan.collections.sets;

9.9.

273


. sets sets.js.
collections.sets,
collections/ ( maps.js).
, com.davidflanagan.collections.sets,
com/davidflanagan/collections/sets.js.

9.9.2.


(API): , , ,
.
,
.
Set._v2s() 9.6 ,
Set ,
.
, ( Set)
. 8.5, ,
,
. , (
)
. 9.24 ,
Set.
9.24. Set
// Set ,
// . , , ,
// ,
// , . ,
// , , "invocation"
// .
var Set = (function invocation() {
function Set() { // - - .
this.values = {}; //
this.n = 0; //
this.add.apply(this, arguments); // ,
} //
// Set.prototype.
//
Set.prototype.contains = function(value) {
// , v2s() Set._v2s()
return this.values.hasOwnProperty(v2s(value));
};
Set.prototype.size = function() { return this.n; };
Set.prototype.add = function() { /* ... */ };
Set.prototype.remove = function() { /* ... */ };
Set.prototype.foreach = function(f, context) { /* ... */ };

274

9.

// ,
// . API
// ,
// Set .
function v2s(val) { /* ... */ }
function objectId(o) { /* ... */ }
var nextId = 1;
// API - Set().
//
// , .
//
// .
// .
return Set;
}()); // .

,
JavaScript. ,
, (function() {
}());. ,
, ,
, . 9.24
invocation, ,
.
namespace, , .
,
API
. 9.24 ,
.
,
. , API,
.
:
// , ,
//
var collections;
if (!collections) collections = {};
// sets
collections.sets = (function namespace() {
// ,
//
// ... ...
// API
return {
// :
AbstractSet: AbstractSet,
NotSet: NotSet,
AbstractEnumerableSet: AbstractEnumerableSet,
SingletonSet: SingletonSet,
AbstractWritableSet: AbstractWritableSet,

9.9.

275

ArraySet: ArraySet
};
}());

,
, new
:
var collections;
if (!collections) collections = {};
collections.sets = (new function namespace() {
// ... ...
// API this
this.AbstractSet = AbstractSet;
this.NotSet = NotSet; // ....
// .
}());

,

:
var collections;
if (!collections) collections = {};
collections.sets = {};
(function namespace() {
// ... ...
// API ,
collections.sets.AbstractSet = AbstractSet;
collections.sets.NotSet = NotSet; // ...
// return , .
}());

, ,
API .
provides(), API,
exports, API. Java
Script ,
,
.

10
10.

, .
RegExp JavaScript ,
String RegExp ,
.
JavaScript
, Perl 5,
, Perl,
JavaScript.1
,
.
String RegExp,
.

10.1.
JavaScript RegExp.
RegExp RegExp(),
.
, ,
,
(/). , JavaScript- , :
var pattern = /s$/;

Perl,
ECMAScript, s ( ) x ( );
\a, \e, \l, \u, \L, \U, \E, \Q, \A, \Z, \z \G; (?<=
(?<!
; (?# , (?.

10.1.

277

RegExp pattern.
RegExp , s.

RegExp():
var pattern = new RegExp("s$");


. , -,
, .
/java/ , java.

, . ,
/s$/ . , s,
. , $, , .
, ,
s.
,
JavaScript.

RegExp
, ,
, .
( ), {} [],
. var a = [] ,
, .
. ECMA
Script3 , RegExp RegExp
,
RegExp, .
ECMAScript 5 ,
, RegExp,
. IE
, ECMAScript5,
, ,
.

10.1.1.
,
. JavaScript

,
(\). , \n
. .10.1.

278

10.

10.1.

\0

NUL (\u0000)

\t

(\u0009)

\n

(\u000A)

\v

(\u000B)

\f

(\u000C)

\r

(\u000D)

\xnn

Latin,
nn; , \x0A , \n

\uxxxx

Unicode-, xxxx;
, \u0009 , \t

\cX

^X; , \cJ
\n

:
^ $ . * + ? = ! : | \ / ( ) [ ] { }

.

, . , ,
-
, . ,
@,
.
,
\, .
,
, ,
, \.
, , ,
. ,
, : /\\/.

10.1.2.

.
, . , /[abc]/
a, b c.
, , ,
. ^
, . /[^abc]/

10.1.

279

, a, b c.
.

/[a-z]/, Latin
/[a-zA-Z0-9]/.
,
JavaScript
(escape) . , \s
, Unicode, \S
, Unicode.
.10.2
. ( ,
ASCII-
Unicode-. Unicode, , /[\u0400-\04FF]/
.)
10.2.

[...]

[^...]

, Unicode-

\w

ASCII-. [a-zA-Z0-9_]

\W

, ASCII-.
[^a-zA-Z0-9_]

\s

Unicode

\S

Unicode. ,
\w \S

\d

ASCII-. [0-9]

\D

, ASCII-. [^0-9]

[\b]

( )

,
. \s
, \d , , /[\s\d]/
.
. , \b .
, .
, ,
: /[\b]/.

10.1.3.
,
, /\d\d/

280

10.

/\d\d\d\d/, , , ,
, , .
,
,
.
, , ,
. ,
. , +
. . 10.3
.
10.3.

{n,m}

, n
m

{n,}

, n

{n}

;
. {0,1}

.
{1,}

.
{0,}

:
/\d{2,4}/ //
/\w{3}\d?/ //
//
/\s+java\s+/ //
//
/[^(]*/ //
//

,


"java"

,

* ?.
, ,
. , /a*/
bbbb, a!

10.1.3.1.
, . 10.3,
,
. ,
. ,
. ( )
: ??, +?, *? {1,5}?. ,
/a+/ a.
aaa, . , /a+?/

10.1.

281

a
. ,
a.
.
/a+b/, a,
b. aaab .
/a+?b/. ,
b, a.
aaab ,
a b.
, . ,

,
. , ,
, ,
.

10.1.4. ,

,
. | .
, /ab|cd|ef/ ab, cd,
ef, /\d{3}|[a-z]{4}/ , .
, ,
.
,
. , ab /a|ab/,
.
.
,
|, *, +, ?
. , /java(script)?/ java,
script, /(ab|cd)+|ef)/
ef, ab cd.

.
, ,
, . ( ,
, .) ,
,
. /[a-z]+\d+/.
, .
(/[a-z]+(\d+)/),
. ,
.

282

10.

,

.
\.
. , \1 , \3 .
, ,
. ,
([Ss]cript)
\2:
/([Jj]ava([Ss]cript)?)\sis\s(fun\w*)/


, , .
, ,
. ,

. ,
(..
):
/['"][^'"]*['"]/

:
/(['"])[^'"]*\1/

\1 .
, ,
.
, .
, .. :
/(['"])[^\1]*\1/

,

.

.
( ) (?: ).
, , :
/([Jj]ava(?:[Ss]cript)?)\sis\s(fun\w*)/

(?:[Ss]cript) ,
?.
, \2
, (fun\w*).
.10.4 ,
.

10.1.

283

10.4. ,


|

. ,
.

(...)

. ,
*, +, ?, | .. ,
.

(?:...)

. ,
, .

\n

,
n. (,
).
. , (?:, .

10.1.5.
,
. , \s
.
, . , \b
\w ( ASCII-) \W ( )
ASCII- .1
, \b, - ,
,
.
,
. , ^
$, .
, JavaScript, ,
/^JavaScript$/.
Java ( , JavaScript),
/\sJava\s/, 2 .
. -, Java,
,
. -,
,
, , . ,
\s, ( ),
\b. : /\bJava\b/.
\B , .

( ), \b
.

, . . . .

284

10.

/\B[Ss]cript/ JavaScript post


script script Scripting.

. (?= ),
,
, ,
. ,
, ,
/[Jj]ava([Ss]cript)?(?=\:)/.
JavaScript JavaScript: The Definitive Guide, Java Java in a Nutshell,
.
(?!,
, , . , /Java(?!Script)([A-Z]\w*)/
Java,
ASCII- , Java
Script. JavaBeans,
Javanese, JavaScrip, Java
Script JavaScripter.
.10.5 .
10.5.

\b

, .. \w
\W \w . (
, [\b] .)

\B

, .

(?=p)

. ,
p,
.

(?!p)

. ,
p.

10.1.6.
, .
.
,
, . JavaScript
. i ,
, g ,

10.2. String

285

.. . m
. ,
, ,
^ $, ,
, .
, /java$/im java, Java\nis fun.
. ,
java ( Java, JAVA ..)
,
/\bjava\b/i.
, g: /\bjava\b/gi.
.10.6 . ,
g
String RegExp, .
10.6.

, .

, .. ,
.

. ^
, $ .

10.2. String

, ,
JavaScript-.
String,
, .
, RegExp,
. ,
, .
, .
, .
search().

, 1, . , 4:
"JavaScript".search(/script/i);

search() ,
RegExp. search()
g .
replace() .
, .

286

10.

, ,
. g, replace()
.
. replace()
, ,
,
RegExp(), search().
replace()
JavaScript :
//
text.replace(/JavaScript/gi, "JavaScript");

replace() ,
. , ,
, ,
,
. $ , replace()
, .
. , ,
,
ASCII-:
// , ,
// ( ), .
var quote = /"([^"]*)"/g;
//
// , $1.
text.replace(quote, "$1");

replace() ,
, String.replace().
, , replace() ,
.
match() String,
.
( ,
RegExp()) ,
. g,
, . :
"1 2 3".match(/\d+/g) // ["1", "2", "3"]

g, match()
; . match()
, .
,
. match()
a, a[0] , a[1]
, , ..
replace(), , a[n] $n.

10.3. RegExp

287

, ,
URL-:
var url = /(\w+):\/\/([\w.]+)\/(\S*)/;
var text = " http://www.example.com/~david";
var result = text.match(url);
if (result != null) {
var fullurl = result[0]; // "http://www.example.com/~david"
var protocol = result[1]; // "http"
var host = result[2]; // "www.example.com"
var path = result[3]; // "~david"
}

, ,
g , match() ,
exec() : index
input, exec() .
String,
, split(). , ,
, . :
"123,456,789".split(","); // ["123","456","789"]

split()
. . , ,
:
"1, 2, 3 , 4 ,5".split(/\s*,\s*/); // ["1","2","3","4","5"]

split() .
String.split().

10.3. RegExp
,
RegExp. RegExp(), RegExp
. RegExp
.
RegExp()
RegExp. ,
, .. ,
. ,

\, ,
RegExp() ,
\ \\. RegExp()
. , .
g, i, m . :
// .
// \\
var zipcode = new RegExp("\\d{5}", "g");

288

10.

RegExp() ,

. , ,
,
RegExp().

10.3.1. RegExp
RegExp . source ,
, . global
, ,
g . ignoreCase ,
, i
. multiline , ,
m .
lastIndex , .
g ,
. , exec() test().

10.3.2. RegExp
RegExp , ;
String, .
RegExp, , exec().
match() String, ,
RegExp, ,
String, RegExp. exec()
, .. .
, null. ,
, , match()
g. ,
, ,
. , index
, , input
, .
match(), exec() ,
g. ,
match()
. exec() ,
. exec()
, g, lastIndex
,
. exec()
, ,
lastIndex. exec() , last
Index 0. ( lastIndex
, , ,
,
RegExp.)

10.3. RegExp

289

exec()
. :
var pattern = /Java/g;
var text = "JavaScript , Java!";
var result;
while((result = pattern.exec(text)) != null) {
alert(" `" + result[0] + "'" +
" " + result.index +
"; " + pattern.lastIndex);
}

RegExp test(), exec().


true,
:
var pattern = /java/i;
pattern.test("JavaScript"); // true

test() exec(), true, exec()


null. test() , exec()
:
, lastIndex, ,
lastIndex ,
. test()
, exec().
search(), replace() match() String lastIndex,
exec() test(). String
lastIndex 0. exec() test() ,
g, ,
, lastIndex
( ,
), lastIndex .
,
, . g,
. , ECMAScript5,
,
RegExp, lastIndex,
lastIndex .

11
11.

JavaScript

JavaScript,
ECMAScript 3 ECMAScript 5. , ,
JavaScript.
, ,
: ,
, ,
, . 11.1
.
ECMAScript 3 1999, ,
ECMAScript 5, 2009.
(Brendan Eich), JavaScript,
( ECMAScript
) Mozilla JavaScript
1.5, 1.6, 1.7, 1.8 1.8.1 Firefox1.0, 1.5, 2, 3 3.5.
JavaScript ECMAScript 5,
. , ,
.
Firefox, ,
Spidermonkey JavaScript. Mozilla
Rhino JavaScript, Java (12.1),
. ,
, -
, -
. , :
;
;
Firefox;
JavaScript,
Spidermonkey Rhino (12.1).

11.1. JavaScript

291

,
. ,
,
, , .

11.1. JavaScript

,
. ,
. ,
,
.

11.1.1. The Good Parts


(Douglas Crockford) JavaScript: The Good
Parts (OReilly) JavaScript, ,
, , .
,
, . :

. , ,
.

with continue,
eval().
.
,
: ,
. , ,
, .
, ++
--. == != -

=== !==.
JavaScript ,
var
,
var
.
, ,
.
-
(http://jslint.com)
Good Parts.
, JSLint
, .

292

11. JavaScript

, ECMAScript 5
, JavaScript,
,
. , ECMAScript 5, JSLint
, use strict,
The Good Parts.

11.1.2.
Good Parts ,
.
,
JavaScript
, .
,
.
,
, ,
. ,
, ,
,
, , ,
,

. ,
,
.
,
JavaScript :

eval() Function(),
,
.

this, ( ) this
.

.

with,
.

. JavaScript
,
window. document ,
.
, ,
.

11.1. JavaScript

293

, document.
,
,
, -, .
, ,
, docu
ment, DOM API.

,
.
caller callee arguments (
arguments),
call() apply() , constructor prototype.
, , __proto__.

.
, .
,
.
[] ,

.
,
.
[] ,

, ,
.
,
eval() with, ,

JavaScript. ,
, ,
.
, ,
, .

this. ,
.
.
,
:
ADsafe
ADsafe (http://adsafe.org)
.
(Douglas Crockford) ( The Good
Parts). ADsafe ,

294

11. JavaScript

JSLint (http://jslint.org).

ADSAFE, ,
DOM . ADsafe
,

.
dojox.secure
dojox.secure (http://www.sitepen.com/blog/2008/08/01/secure-ma
shups-with-dojoxsecure/) Dojo (http://dojotool
kit.org),
ADsafe. ADsafe,
. ADsafe,
DOM API. ,
, JavaScript,

.
Caja
Caja (http://code.google.com/p/google-caja/) ,
,
Google. Caja (- )
. Cajita ( )
, ,
ADsafe dojox.secure. Valija ( )
, ECMAScript5
( eval()). Caja ,
- (HTML, CSS JavaScript)
, -, ,
.
Caja OpenSocial API (http://code.google.com/apis/open
social/); Yahoo! -. ,
, http://my.yahoo.com,
Caja.
FBJS
FBJS JavaScript, Facebook
(http://facebook.com)
. FBJS
.
,

this.
, , .

, .
, , eval()
. FBJS
DOM API.

11.2.

295

Microsoft Web Sandbox


Microsoft Web Sandbox (http://websandbox.livelabs.com/)
JavaScript ( HTML CSS)

, JavaScript
.

11.2.
. Java
Script 1.5 const
. , ,
(
), :
const pi = 3.14; //
pi = 4; //
const pi = 4; //
var pi = 4; //

.
.
.
.

const var:

(3.10.1).
JavaScript
, JavaScript 1.7
let, . const
( ) JavaScript,
,
. let ,
1.7.
let :
, var;
for for/in, var;
,
;
,
.
let
var. , var,
. ,
let, (,
, ). let
, , ,
:
function oddsums(n) {
let total = 0, result=[]; //
for(let x = 1; x <= n; x++) { // x

296

11. JavaScript

let odd = 2*x-1; // odd


total += odd;
result.push(total);
}
// x odd
// ReferenceError
return result;
}
oddsums(5); // [1,4,9,16,25]

, let ,
var for. ,

. let for/in (for each;
11.4.1):
o = {x:1,y:2};
for(let p in o) console.log(p); // x y
for each(let v in o) console.log(v); // 1 2
console.log(p) // ReferenceError: p

, let
let
. let

. for
. ,

:
let x = 1;
for(let x = x + 1; x < 5; x++)
console.log(x); // 2,3,4
{ // ,
let x = x + 1; // x , x+1 = NaN
console.log(x); // NaN
}

, var,
, , , var
. (
ReferenceError),
var undefined. ,
let, :
let ( ,
let), , undefined.
, let

.
let,
. , let (

11.2.

297

let, ),

.
, :
let x=1, y=2;
let (x=x+1,y=x+2) { // ,
console.log(x+y); // 5
};
console.log(x+y); // 3

, let-
.
x, ,
, x.
let
let-,
, .
let-,
, :
let x=1, y=2;
console.log(let (x=x+1,y=x+2) x+y); // 5

const let (
, )
ECMAScript.

JavaScript
- JavaScript
, Mozilla
Spidermonkey Rhino - Firefox.
, ,
( let), ,
,
, JavaScript ,
.
Spidermonkey Rhino,
version().
( , .
let,
JavaScript 1.7, .. 170.) Firefox
script:
<script type="application/JavaScript; version=1.8">

298

11. JavaScript

11.3.
Spidermonkey 1.7
, . (
Python Ruby.)

( ),
,
.
(
) ,
. , ,

var let.

, ,
.
.
, , .

:
let [x,y] = [1,2]; //
[x,y] = [x+1,y+1]; //
[x,y] = [y,x]; //
console.log([x,y]); //

, let x=1, y=2


, x = x + 1, y = y+1

[3,2]

,
, :
// [x,y] [r,theta]
function polar(x,y) {
return [Math.sqrt(x*x+y*y), Math.atan2(y,x)];
}
//
function cartesian(r,theta) {
return [r*Math.cos(theta), r*Math.sin(theta)];
}
let [r,theta] = polar(1.0, 1.0); // r=Math.sqrt(2), theta=Math.PI/4
let [x,y] = cartesian(r,theta); // x=1.0, y=1.0


.
undefined,
.
, :
let [x,y] = [1]; // x = 1, y = undefined
[x,y] = [1,2,3]; // x = 1, y = 2
[,x,,y] = [1,2,3,4]; // x = 2, y = 4

11.3.

299

JavaScript ,
(
). , ,
y [2,3].

, , .
, :
let first, second, all;
all = [first,second] = [1,2,3,4]; // first=1, second=2, all=[1,2,3,4]


.
:
let [one, [twoA, twoB]] = [1, [2,2.5], 3]; // one=1, twoA=2, twoB=2.5

,
.
: , ,
. ,
. ,
, ,
( undefined) .
,

. , r, g b ,
red, green blue :
let transparent = {r:0.0, g:0.0, b:0.0, a:1.0}; // RGBA
let {r:red, g:green, b:blue} = transparent; // red=0.0,green=0.0,blue=0.0

Math

:
// , let sin=Math.sin, cos=Math.cos, tan=Math.tan
let {sin:sin, cos:cos, tan:tan} = Math;


,
. ,
. :
// :
let data = {
name: " ",
type: "",
impl: [{engine: "spidermonkey", version: 1.7},
{engine: "rhino", version: 1.7}]
};
//
//
let ({name:feature, impl: [{engine:impl1, version:v1},{engine:impl2}]} = data) {
console.log(feature); // " "

300

11. JavaScript

console.log(impl1); // "spidermonkey"
console.log(v1); // 1.7
console.log(impl2); // "rhino"
}

,
,
. ,
.
( ).
,
, .
,
, .
,
, ,
:
,
.

11.4.
Mozilla JavaScript
, for each,
Python. .

11.4.1. for/each
for/each , E4X. E4X
(ECMAScript for XML) ,
JavaScript XML
XML. E4X
-, JavaScript Mozilla,
1.6 (Firefox1.5). for/
each ,
XML. E4X 11.7.
for each for/in.
:
let o = {one: 1, two: 2, three: 3}
for(let p in o) console.log(p); // for/in: 'one', 'two', 'three'
for each (let v in o) console.log(v); // for/each: 1, 2, 3

for/each
( ) .
,
:
a = ['', '', ''];
for(let p in a) console.log(p); // 0, 1, 2
for each (let v in a) console.log(v); // '', '', ''

11.4.

301

, for/each

, , .
for/each
. ,
JavaScript ECMAScript 5,
. (
for/in 7.6.)

11.4.2.
JavaScript 1.7 for/in
. for/in JavaScript 1.7 for/in
Python, .
,
.
,

. next(). next()
. , counter(),
, , , ,

next(). ,
, :
// , ;
function counter(start) {
let nextValue = Math.round(start); //
return { next: function() { return nextValue++; }}; //
}
let serialNumberGenerator = counter(1000);
let sn1 = serialNumberGenerator.next(); // 1000
let sn2 = serialNumberGenerator.next(); // 1001

next()
StopIteration,
. StopIteration Java
Script 1.7. ( ),
.
, StopIteration -, TypeError()
RangeError(). rangeIter(),
, :
// ,
function rangeIter(first, last) {
let nextValue = Math.ceil(first);
return {
next: function() {
if (nextValue > last) throw StopIteration;
return nextValue++;
}

302

11. JavaScript

};
}
// .
let r = rangeIter(1,5); // -
while(true) { //
try {
console.log(r.next()); // next()
}
catch(e) {
if (e == StopIteration) break; // StopIteration
else throw e;
}
}

, -
- StopIteration. -
.
.
, .
__iterator__() (
), - .
JavaScript 1.7 for/in
. in
, for/in __iterator__(),
-. next()
,
. for/in StopIteration,
, .
range(), ( ),
. ,
for/in
while, .
// ,
function range(min,max) {
return { // , .
get min() { return min; }, //
get max() { return max; }, // .
includes: function(x) { // .
return min <= x && x <= max;
},
toString: function() { // .
return "[" + min + "," + max + "]";
},
__iterator__: function() { //
let val = Math.ceil(min); // . .
return { // -.
next: function() { // .
if (val > max) // -
throw StopIteration;
return val++; //
} //

303

11.4.
};
}
};
}
// , :
for(let i in range(1,10)) console.log(i); // 1 10

, , __iterator__()
StopIteration
, ( ) __iterator__()
/ StopIteration for/in.
- -
, Iterator(). (Iterator()
, JavaScript 1.7.)
, __iterator__(),
. (
Iterator() , __iterator__().)
Iterator() .
( ), __iterator__(),
. next()
.
,
. ,
for/in next(), ,
Iterator()

:
for(let [k,v] in Iterator({a:1,b:2})) //
console.log(k + "=" + v); // "a=1" "b=2"

, Iterator(),
. -,
, . -,
Iterator() true ,
, .
:
o = {x:1, y:2} //
Object.prototype.z = 3; //
for(p in o) console.log(p); //
for(p in Iterator(o, true)) console.log(p); //


z
"x", "y" "z"
"x" "y"

11.4.3.
JavaScript 1.7 ( Python),
yield. ,
, 1.7,
11.2. yield
return, .
yield return , ,

304

11. JavaScript

yield, ,
.
yield
. ,
.
.
, yield (
yield ), -.
- yield.
return , ,
, return .
yield
return, -
: function, typeof
function
Function.prototype. -
: ,
, - .
, -
. next(),
- ,
yield. , yield
- next()
. - return
, next()
StopIteration.
, next(),
StopIteration, , .1
, ..
for/in. ,
- ,
yield:
// -
//
function range(min, max) {
for(let i = Math.ceil(min); i <= max; i++) yield i;
}
// -, , .
for(let n in range(3,8)) console.log(n); // 3 8.

-,
-. -
.
, -,
-.

11.4.

305

- .

:
// -,
function fibonacci() {
let x = 0, y = 1;
while(true) {
yield y;
[x,y] = [y,x+y];
}
}
// -, .
f = fibonacci();
// , 10 .
for(let i = 0; i < 10; i++) console.log(f.next());

, - fibonacci() .

StopIteration. ,
for/in ,
next() .
, f -
-.
, close() f:
f.close();

close()
-, return ,
. try,
finally , close() .
close() , finally
, close().

, ,
.. ,
Unix. ,
: (
) , .
11.1.
11.1.
// , .
// , s.split(),
// , ,
// .
function eachline(s) {
let p;
while((p = s.indexOf('\n')) != -1) {
yield s.substring(0,p);
s = s.substring(p+1);

306

11. JavaScript

}
if (s.length > 0) yield s;
}
// -, f(x) x i
function map(i, f) {
for(let x in i) yield f(x);
}
// -, i, f(x) true
function select(i, f) {
for(let x in i) {
if (f(x)) yield x;
}
}
//
let text = " #comment \n \n hello \nworld\n quit \n unreached \n";
// .
//
let lines = eachline(text);
//
let trimmed = map(lines, function(line) { return line.trim(); });
// ,
let nonblank = select(trimmed, function(line) {
return line.length > 0 && line[0] != "#"
});
// ,
// , "quit".
for (let line in nonblank) {
if (line === "quit") break;
console.log(line);
}

: ,
-, ,
.
. send(),
next(). ,
send() , ,
yield -. ( ,
, yield
. yield ,
.) next() send()
throw(). ,
yield throw() ,
:
// -, .
// send() .
// throw("reset") .
// - throw() .
function counter(initial) {

307

11.4.

let nextValue = initial; //


while(true) {
try {
let increment = yield nextValue; //
if (increment) // ...
nextValue += increment; // ... .
else nextValue++; // 1
}
catch (e) { //
if (e==="reset") // throw()
nextValue = initial;
else throw e;
}
}
}
let c = counter(10); //
console.log(c.next()); //
console.log(c.send(2)); //
console.log(c.throw("reset")); //

10
10
12
10

11.4.4.
, JavaScript 1.7 Python,
.
.
, ..
,
JavaScript.
, .
,
range() ,
, 100:
let evensquares = [x*x for (x in range(0,10)) if (x % 2 === 0)]

:
let evensquares = [];
for(x in range(0,10)) {
if (x % 2 === 0)
evensquares.push(x*x);
}

:
[ for ( in ) if ( ) ]

:
for/in for/each .
(
) in (
, ) in.
,

308

11. JavaScript

,
. ,
var let
let,
.
if

. ,
, .
,
for. false,
. if
, ,
if (true).

, for,
. , ,
,
,
.
,
:
data = [2,3,4, -5]; //
squares = [x*x for each (x in data)]; // : [4,9,16,25]
//
roots = [Math.sqrt(x) for each (x in data) if (x >= 0)]
//
o = {a:1, b:2, f: function(){}}
let allkeys = [p for (p in o)]
let ownkeys = [p for (p in o) if (o.hasOwnProperty(p))]
let notfuncs = [k for ([k,v] in Iterator(o)) if (typeof v !== "function")]

11.4.5. -
JavaScript 1.81
-. -
(
),
, . -
,
,
.
, .
, ,
: n- , n-1 .
map():
// -, f(x) x i
1

- Rhino.

11.5.

309

function map(i, f) {
for(let x in i) yield f(x);
}

-
map(). h,
f(x) x, g,
:
let h = (f(x) for (x in g));

eachline() 11.1,
, ,
:
let lines = eachline(text);
let trimmed = (l.trim() for (l in lines));
let nonblank = (l for (l in trimmed) if (l.length > 0 && l[0]!='#'));

11.5.
JavaScript 1.81 (
).
, return ,
,
. :
let succ = function(x) x+1, yes = function() true, no = function() false;

: , ,
,
return. ,
, . :
//
data.sort(function(a,b) b-a);
// ,
let sumOfSquares = function(data)
Array.reduce(Array.map(data, function(x) x*x), function(x,y) x+y);

11.6. catch
JavaScript 1.5 try/catch
catch. , ,
catch if
:
try {
//
throw 1;
1

Rhino.

310

11. JavaScript

}
catch(e if e instanceof ReferenceError) {
//
}
catch(e if e === "quit") {
// , "quit"
}
catch(e if typeof e === "string") {
//
}
catch(e) {
//
}
finally {
// finally
}

- ,
catch. catch
. true,
catch, catch . catch
, if true
, catch,
. catch
true,
. , ,
catch,
, if.

11.7. E4X: ECMAScript for XML


ECMAScript for XML, E4X,
1 JavaScript,
XML-. E4X Spider
monkey 1.5 Rhino 1.6. -
, E4X, ,
, Spidermonkey Rhino.
E4X XML- ( XML) XML, XML (
XML, ) XMLList.

XML. XML ,
E4X ( ) . ,
JavaScript, ,
typeof object. XML, ,
JavaScript, typeof
1

E4X ECMA-357.
http://www.ecma -international.org/publications/standards/Ecma357.htm.

11.7. E4X: ECMAScript for XML

311

xml. , XML DOM (Do


cument Object Model ),
JavaScript (15). E4X
XML- E4X
DOM, Firefox . ,
E4X .

E4X . ,
XML XMLList ,
. . ,
E4X,
.
E4X .

XML JavaScript
XML, :
// XML
var pt =
<periodictable>
<element id="1"><name></name></element>
<element id="2"><name></name></element>
<element id="3"><name></name></element>
</periodictable>;
//
pt.element += <element id="4"><name></name></element>;

XML E4X
, XML
JavaScript.
XML, :
pt = <periodictable></periodictable>; //
var elements = ["", "", ""]; //
// XML,
for(var n = 0; n < elements.length; n++) {
pt.element += <element id={n+1}><name>{elements[n]}</name></element>;
}


XML.
:
pt.element += new XML('<element id="5"><name></name></element>');

XML XML()
XMLList():
pt.element += new XMLList('<element id="6"><name></name></element>' +
'<element id="7"><name></name></element>');

XML-
E4X:

312

11. JavaScript

var elements = pt.element; // <element>


var names = pt.element.name; // <name>
var n = names[0]; // "": <name> 0.

, E4X
XML. .. .
. :
// <name>
var names2 = pt..name;

E4X :
// <element>.
// <name>.
var names3 = pt.element.*;

E4X @
( XPath). ,
, :
//
var atomicNumber = pt.element[1].@id;

@*:
// <element>
var atomicNums = pt.element.@*;

E4X

-:
// ,
// id < 3
var lightElements = pt.element.(@id < 3);
// <element> , ,
// "". <name>
// <element>.
var bElementNames = pt.element.(name.charAt(0) == '').name;

for/each, ( 11.4.1),
E4X
XML. , for/each for/in, ,

:
//
for each (var e in pt.element) {
console.log(e.name);
}
//
for each (var n in pt.element.@*) console.log(n);

E4X
.
:

11.7. E4X: ECMAScript for XML

313

// <element> -
// , :
//
// <element id="1" symbol="">
// <name></name>
// <weight>1.00794</weight>
// </element>
//
pt.element[0].@symbol = "";
pt.element[0].weight = 1.00794;

,
delete:
delete pt.element[0].@symbol; //
delete pt..weight; // <weight>

E4X ,
XML .
E4X ,
XML. , insertChildBefore():
pt.insertChildBefore(pt.element[1],
<element id="1"><name></name></element>);

E4X ,
XML:
//
// "default xml namespace" statement:
default xml namespace = "http://www.w3.org/1999/xhtml";
// xhtml svg:
d = <html>
<body>
:
<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10">
<rect x="0" y="0" width="10" height="10" fill="red"/>
</svg>
</body>
</html>
// body uri
var tagname = d.body.name();
var bodyns = tagname.uri;
var localname = tagname.localName;
// <svg> ,
// . svg
// Namespace
// ::
var svg = new Namespace('http://www.w3.org/2000/svg');
var color = d..svg::rect.@fill // "red"

12
12.

JavaScript

JavaScript,
, , Java
Script -, API
JavaScript. JavaScript ,
JavaScript -
. JavaScript
, , JavaScript
. ,
JavaScript,
JavaScript. Rhino JavaScript,
Java, JavaScript
Java. Rhino 12.1. Node
V8 JavaScript, Google,
POSIX (Unix) API
, , ,
/,
HTTP. Node 12.2.
, JavaScript,
Node
Rhino. ,
-. , Rhino,
, Swing
Java. Node
JavaScript, ,
.
,
-, JavaScript.
Rhino
Node,
. , -

12.1. Java Rhino

315

Java POSIX API, Rhino


, Java,
Node
Unix.

12.1. Java Rhino


Rhino JavaScript, Java,
JavaScript,
Java. Rhino
JavaScript Java
, JavaScript
Java.
Rhino ,
JavaScript:
// , :
// help() rhino,
print(x); //
version(170); // Rhino 1.7
load(filename,...); //
// JavaScript
readFile(file); //
readUrl(url); // URL
//
spawn(f); // f() f
//
runCommand(cmd, //
[args...]); //
quit() // Rhino

Rhino
Rhino ,
Mozilla. http://www.
mozilla.org/rhino/. Rhino1.7r2 ECMAScript3
, 11. Rhino
, .

1.7r3,
ECMAScript5.
Rhino JAR-. ,
:
java -jar rhino1_7R2/js.jar program.js

program.js, Rhino
,
.

316

12. JavaScript

print():
console.log(). Rhino Java
JavaScript:
// Packages Java
Packages.any.package.name // CLASSPATH
java.lang // java Packages.java
javax.swing // javax Packages.javax
// :
var System = java.lang.System;
var JFrame = javax.swing.JFrame;

JavaScript,
, .
:
var ArrayList = java.util.ArrayList; //
importClass(java.util.HashMap); // : var HashMap=java.util.HashMap
// () importPackage().
// java.lang:
// JavaScript.
importPackage(java.util);
importPackage(java.net);
// :
// JavaImporter() with
var guipkgs = JavaImporter(java.awt, java.awt.event, Packages.javax.swing);
with (guipkgs) {
/* , Font, ActionListener JFrame */
}

new
Java, JavaScript:
// : Java new
var f = new java.io.File("/tmp/test"); //
var out = new java.io.FileWriter(f);

Rhino JavaScript- instanceof


Java:
f instanceof java.io.File // => true
out instanceof java.io.Reader // => false: Writer, Reader
out instanceof java.io.Closeable // => true: Writer Closeable

,
Rhino Java
JavaScript. (
, Rhino : Ja
vaScript- /tmp/test java.
lang.String.) Java Java, Rhino
JavaScript Java:
// Java JavaScript
java.lang.System.getProperty("java.version") // Java

12.1. Java Rhino

317

var isDigit = java.lang.Character.isDigit; // .


isDigit("") // => true: 2
// f out Java,
out.write("Hello World\n");
out.close();
var len = f.length();

, Rhino
Java- Java- Java
Script. Java ,
. Java-
, Rhino , Java
Script:
// Java-
var stdout = java.lang.System.out;
// Rhino JavaScript
f.name // => "/tmp/test": f.getName()
f.directory // => false: f.isDirectory()

Java ,
, . Rhino
, ,
, JavaScript.
:
// , Java- o f,
// . JavaScript :
o['f(int)'](3); // ,
o['f(float)'](Math.PI); // ,

, Java-
for/in:
importClass(java.lang.System);
for(var m in System) print(m); // java.lang.System
for(m in f) print(m); // java.io.File
// ,
for (c in java.lang) print(c); //

Rhino JavaScript
Java-, JavaScript-. ,
Java- JavaScript-:
, , JavaScript-
, slice(). JavaScript ,
Rhino Java-
JavaScript,
java.lang.reflect.Array:
// 10 128
var words = java.lang.reflect.Array.newInstance(java.lang.String, 10);
var bytes = java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, 128);

318

12. JavaScript

// JavaScript-:
for(var i = 0; i < bytes.length; i++) bytes[i] = i;

Java .

,
. ,
:
// : :
var handler = new java.awt.event.FocusListener({
focusGained: function(e) { print("got focus"); },
focusLost: function(e) { print("lost focus"); }
});
//
var handler = new java.awt.event.WindowAdapter({
windowClosing: function(e) { java.lang.System.exit(0); }
});
// ,
button.addActionListener(function(e) { print("button clicked"); });
// ,
// ,
// Rhino
frame.addWindowListener(function(e, name) {
if (name === "windowClosing") java.lang.System.exit(0);
});
// , ,
// JavaAdapter:
var o = new JavaAdapter(java.awt.event.ActionListener, java.lang.Runnable, {
run: function() {}, // Runnable
actionPerformed: function(e) {} // ActionListener
});

Java- , Rhino
JavaScript-. Java java.lang.Exception javaException JavaScript-
Error:
try {
java.lang.System.getProperty(null); // null -
}
catch(e) { // e - JavaScript-
print(e.javaException); // java.lang.NullPointerException
}


Rhino. Rhino ,
null. Java- char JavaScript
, JavaScript . JavaScript-
Java-, (
) Java- java.lang.String

12.1. Java Rhino

319

JavaScript-. ,
:
var version = java.lang.System.getProperty("java.version");

version
java.lang.String. JavaScript-,
. -, Java- length length().
-, typeof object Java-. Java-
JavaScript- toString(),
Java- toString(),
java.lang.String. Java- ,
JavaScript- String():
var version = String(java.lang.System.getProperty("java.version"));

12.1.1. Rhino
12.1 Rhino,
, .
javax.swing
, java.net ,
java.io / Java
,
URL . .12.1
, .

.12.1. , Rhino
12.1. Rhino
/*
* ,
* Java
*/
// Swing
//
importPackage(javax.swing);
importClass(javax.swing.border.EmptyBorder);
importClass(java.awt.event.ActionListener);
importClass(java.net.URL);
importClass(java.io.FileOutputStream);
importClass(java.lang.Thread);
//
var frame = new JFrame("Rhino URL Fetcher"); //

320
var urlfield = new JTextField(30); //
var button = new JButton("Download"); //
var filechooser = new JFileChooser(); //
var row = Box.createHorizontalBox(); //
var col = Box.createVerticalBox(); //
//
var padding = new EmptyBorder(3,3,3,3); //

12. JavaScript
URL





//
row.add(urlfield); //
row.add(button); //
col.add(row); //
frame.add(col); //
row.setBorder(padding); //
frame.pack(); //
frame.visible = true; //
// , - .
frame.addWindowListener(function(e, name) {
// , .
if (name === "windowClosing") // Rhino name
java.lang.System.exit(0);
});
// ,
button.addActionListener(function() {
try {
// java.net.URL URL .
// ( )
var url = new URL(urlfield.text);
// URL
var response = filechooser.showSaveDialog(frame);
// , Cancel
if (response != JFileChooser.APPROVE_OPTION) return;
// java.io.File,
var file = filechooser.getSelectedFile();
// url
new java.lang.Thread(function() { download(url,file); }).start();
}
catch(e) {
// , -
JOptionPane.showMessageDialog(frame, e.message, "Exception",
JOptionPane.ERROR_MESSAGE);
}
});
// java.net.URL . URL java.io.File
// . .
// JProgressBar. .
function download(url, file) {
try {
// , ,
// URL,
//
var row = Box.createHorizontalBox(); //

12.2. / Node
row.setBorder(padding); //
var label = url.toString() + ": "; //
row.add(new JLabel(label)); //
var bar = new JProgressBar(0, 100); //
bar.stringPainted = true; //
bar.string = file.toString(); //
row.add(bar); //
col.add(row); //
frame.pack(); //

321


URL
JLabel





// ,
//
bar.indeterminate = true;
//
// ,
var conn = url.openConnection(); // java.net.URLConnection
conn.connect(); //
var len = conn.contentLength; // ,
if (len) { // ,
bar.maximum = len; //
bar.indeterminate = false; //
}
//
var input = conn.inputStream; //
var output = new FileOutputStream(file); //
// 4
var buffer = java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE,
4096);
var num;
while((num=input.read(buffer)) != -1) { // EOF
output.write(buffer, 0, num); //
bar.value += num; //
}
output.close(); //
input.close();
}
catch(e) { // - ,
if (bar) {
bar.indeterminate = false; //
bar.string = e.toString(); //
}
}
}

12.2. /
Node
Node JavaScript, C++,
Unix
, , ,
HTTP.

322

12. JavaScript

, ,
Node Unix ,
, Node,
,
.
, Node
,
.1
,
Node, .
Node
http://nodejs.org/api/.

Node
Node ,
http://nodejs.org.

,
.
Node 0.4.
, ,
, .
Node V8 JavaScript,
Google. Node 0.4 V8 3.1,
ECMAScript5,
.
, Node
, , :
node program.js

Rhino print() load().


Node , :
// , Node
// console.log().
console.log("Hello Node"); //
// load() require().
// ( ) ,
// , .
var fs = require("fs"); // "fs" API
1

JavaScript
, ,
,
JavaScript.

12.2. / Node

323

Node
, , ECMAScript5.

: setTimeout(), setInterval(), clearTimeout() clearInterval():
// .
setTimeout(function() { console.log(", !"); }, 1000);

14.1.
Node -.
Node
process. :
process.version //
process.argv //
process.env //
//
process.pid //
process.getuid() //
process.cwd() //
process.chdir() //
process.exit() //

Node
, argv[0] = "node"
.
: process.env.PATH




( )

, Node,
,
.
.
, ,
, Node ,
( ).
(, setTimeout() )
, Node
.
Node. , Node,
( (emitter) ),
on() .
() - .
-
, API,
, :
emitter.on(name, f) //
//
emitter.addListener(name, f) //
emitter.once(name, f) //
//
emitter.listeners(name) //
emitter.removeListener(name, f) //
emitter.removeAllListeners(name) //

f name,
emitter
: addListener() - on()
,
f
-
f
name

process, , .
:

324

12. JavaScript

// "exit" Node.
process.on("exit", function() { console.log("Goodbye"); });
// ,
// .
// Node .
process.on("uncaughtException", function(e) { console.log(Exception, e); });
// POSIX, SIGINT, SIGHUP SIGTERM,
process.on("SIGINT", function() { console.log("Ignored Ctrl-C"); });

Node
/, /
. ,
, , , .
, s , ,
- . ,
:
// s:
s.on("data", f); //
s.on("end", f); //
//
s.on("error", f); //
s.readable //
s.pause(); //
//
s.resume(); //

f()
"end" ,

- , f()
=> true, -
"data".
,
"data"

// , "data"
//
s.setEncoding(enc); // : "utf8", "ascii" "base64"

, , , ,
. write()
, end() , .
write() . Node

, write() false. ,
,
drain:
// s:
s.write(buffer); //
s.write(string, encoding) //
//
s.end() //
s.end(buffer); //
s.end(str, encoding) //
s.writeable; //
s.on("drain", f) //


.
encoding = "utf-8"
.
.

true, -
f() .

, /,
Node, , .
JavaScript.

12.2. / Node

325

Node Buffer.
Node , , ,
0 255. ,
Node,
, .
,
, ,
,
:
var bytes = new Buffer(256); //
for(var i = 0; i < bytes.length; i++) //
bytes[i] = i; //
var end = bytes.slice(240, 256); //
end[0] //
end[0] = 0; //
bytes[240] //
var more = new Buffer(8); //
end.copy(more, 0, 8, 16); //
more[0] //

256



=> 240: end[0] = bytes[240]

=> 0:

8-15 end[] more[]
=> 248

//
// . : "utf8", "ascii" "base64".
// "utf8".
var buf = new Buffer("2r", "utf8"); // , UTF-8
buf.length // => 3 4
buf.toString() // => "2r":
buf = new Buffer(10); //
var len = buf.write("r2", 4); // , 4-
buf.toString("utf8",4, 4+len) // => "r2":

Node
fs:
var fs = require("fs"); //

.
, Sync,
, .
, Sync,

. ,


:
// . ,
// , .
var text = fs.readFileSync("config.json", "utf8");
// . ,
fs.readFile("image.png", function(err, buffer) {
if (err) throw err; // -
process(buffer); // buffer
});

326

12. JavaScript

writeFile() writeFile
Sync():
fs.writeFile("config.json", JSON.stringify(userprefs));

, ,
Buffer. ,
Node API /.
:
// API /.
// ,
//
function fileCopy(filename1, filename2, done) {
var input = fs.createReadStream(filename1); //
var output = fs.createWriteStream(filename2); //
input.on("data", function(d) { output.write(d); }); //
input.on("error", function(err) { throw err; }); //
input.on("end", function() { //
output.end(); //
if (done) done(); //
});
}

fs ,
, ..
Node
,
:
#! /usr/local/bin/node
var fs = require("fs"), path = require("path"); //
var dir = process.cwd(); //
if (process.argv.length > 2) dir = process.argv[2]; //
var files = fs.readdirSync(dir); //
process.stdout.write("Name\tSize\tDate\n"); //
files.forEach(function(filename) { //
var fullname = path.join(dir,filename); //
var stats = fs.statSync(fullname); //
if (stats.isDirectory()) filename += "/"; //
process.stdout.write(filename + "\t" + //
stats.size + "\t" + //
stats.mtime + "\n"); //
});



.
. -


.




.

#! , .
, Unix, ,
, , ,
. Node ,
.
net API
TCP. (
dgram.)
TCP-, Node:

12.2. / Node

327

// -, Node:
// 2000
// , .
var net = require('net');
var server = net.createServer();
server.listen(2000, function() { console.log(" 2000"); });
server.on("connection", function(stream) {
console.log(" ", stream.remoteAddress);
stream.on("data", function(data) { stream.write(data); });
stream.on("end", function(data) { console.log(" "); });
});

net Node
HTTP http.
, .

12.2.1. Node: HTTP-


12.2 HTTP-,
Node.
URL ,
. http,
Node, API
/, . 18.17,
18, HTTP-.
12.2. HTTP-, Node
//
//
//
//

NodeJS HTTP-,
URL .
http://localhost:8000
http://127.0.0.1:8000

//
var http = require('http'); // API HTTP-
var fs = require('fs'); //
var server = new http.Server(); // HTTP-
server.listen(8000); // 8000.
// Node "on()".
// , .
server.on("request", function (request, response) {
// URL
var url = require('url').parse(request.url);
// URL, .
// .
if (url.pathname === "/test/delay") {
//
// 2000
var delay = parseInt(url.query) || 2000;
//
response.writeHead(200,{"Content-Type": "text/plain; charset=UTF-8"});
//

328

12. JavaScript

response.write(" " + delay + " ...");


// , .
setTimeout(function() {
response.write(".");
response.end();
}, delay);
}
// "/test/mirror", .
// , .
else if (url.pathname === "/test/mirror") {
//
response.writeHead(200,{"Content-Type": "text/plain; charset=UTF-8"});
//
response.write(request.method + " " + request.url +
" HTTP/" + request.httpVersion + "\r\n");
//
for(var h in request.headers) {
response.write(h + ": " + request.headers[h] + "\r\n");
}
response.write("\r\n"); //
// -:
// chunk , .
request.on("data", function(chunk) { response.write(chunk); });
// , .
request.on("end", function(chunk) { response.end(); });
}
// .
else {
// .
var filename = url.pathname.substring(1); // /
var type;
switch(filename.substring(filename.lastIndexOf(".")+1)) { // .
case "html":
case "htm": type = "text/html; charset=UTF-8"; break;
case "js": type = "application/JavaScript;charset=UTF-8"; break;
case "css": type = "text/css; charset=UTF-8"; break;
case "txt" : type = "text/plain; charset=UTF-8"; break;
case "manifest": type = "text/cache-manifest; charset=UTF-8"; break;
default: type = "application/octet-stream"; break;
}
//
// .
// API / fs.createReadStream().
fs.readFile(filename, function(err, content) {
if (err) { // -
response.writeHead(404, { // 404 Not Found
"Content-Type": "text/plain; charset=UTF-8"});
response.write(err.message); //
response.end(); //
}
else { // , .
response.writeHead(200, // MIME
{"Content-Type": type});

12.2. / Node

329

response.write(content); //
response.end(); //
}
});
}
});

12.2.2. Node:
HTTP
12.3 ,
http, GET- POST-
HTTP. httputils,
, :
var httputils = require("./httputils"); // . ".js"
httputils.get(url, function(status, headers, body) { console.log(body); });

require()
eval(). ,
-
.
exports.
API, .1
12.3. httputils Node
//
// "httputils" Node.
//
// HTTP GET- URL
// HTTP,
// . , exports.
exports.get = function(url, callback) {
// URL
url = require('url').parse(url);
var hostname = url.hostname, port = url.port || 80;
var path = url.pathname, query = url.query;
if (query) path += "?" + query;
// GET-
var client = require("http").createClient(port, hostname);
var request = client.request("GET", path, {
"Host": hostname //
});
request.end();
//
request.on("response", function(response) {
// , ,

Node CommonJS ,
http://www.commonjs.org/specs/modules/1.0/.

330

12. JavaScript

response.setEncoding("utf8");
//
var body = ""
response.on("data", function(chunk) { body += chunk; });
//
response.on("end", function() {
if (callback)
callback(response.statusCode, response.headers, body);
});
});
};
// HTTP POST-
exports.post = function(url, data, callback) {
// URL
url = require('url').parse(url);
var hostname = url.hostname, port = url.port || 80;
var path = url.pathname, query = url.query;
if (query) path += "?" + query;
// ,
var type;
if (data == null) data = "";
if (data instanceof Buffer) //
type = "application/octet-stream";
else if (typeof data === "string") //
type = "text/plain; charset=UTF-8";
else if (typeof data === "object") { // /
data = require("querystring").stringify(data);
type = "application/x-www-form-urlencoded";
}
// POST-
var client = require("http").createClient(port, hostname);
var request = client.request("POST", path, {
"Host": hostname,
"Content-Type": type
});
request.write(data); //
request.end();
request.on("response", function(response) { //
response.setEncoding("utf8"); //
var body = "" //
response.on("data", function(chunk) { body += chunk; });
response.on("end", function() { //
if (callback)
callback(response.statusCode, response.headers, body);
});
});
};

II
II.

JavaScript

13 22 JavaScript ,
-. Java
Script-, ,
-.
,
-.
13 JavaScript -
14 Window
15
16
17
18 HTTP
19 jQuery
20
21
22 HTML5

13
13.

JavaScript -

JavaScript.
JavaScript, -
JavaScript (client-side JavaScript). ,
, JavaScript-,
- ; JavaScript-,
- . .
JavaScript -,
-.
; . (

JavaScript, .)
, .
,
,
, , ,
. ,
.
JavaScript.
JavaScript - -
. ,
. , JavaScript
HTML- .
JavaScript:
, .

13.1. JavaScript
Window
JavaScript. - ,
window. Window

334

13. JavaScript -

, location, Location,
URL ,
URL:
// -
window.location = "http://www.oreilly.com/";

, Window , alert(),
, setTimeout(),
:
// 2
setTimeout(function() { alert(", !"); }, 2000);

,
window. Window JavaScript
. , Window

. Window window,
. ,
,
.
Window ,
. 14.
Window document:
Document, ,
. Document , getEle
mentById(), (
HTML ,
), id :
// id="timestamp"
var timestamp = document.getElementById("timestamp");

Element, getElementById(),
, ,
..:
// ,
if (timestamp.firstChild == null)
timestamp.appendChild(document.createTextNode(new Date().toString()));

,
15.
Element style className,
CSS CSS,
. , CSS,
:
//
timestamp.style.backgroundColor = "yellow";
//
// :
timestamp.className = "highlight";

13.1. JavaScript

335

style className, CSS


16.
Window, Document Element
, .
,
.
JavaScript , ,
. , , ,
on, , :
// timestamp,
timestamp.onclick = function() { this.innerHTML = new Date().toString(); }

onload
Window. , ,
,
. JavaScript
onload. 17. 13.1
onload
, CSS
JavaScript. JavaScript
HTML- <script>. 13.2.
, ,
.
JavaScript, .
13.1. JavaScript,

<!DOCTYPE html>
<html>
<head>
<style>
/* CSS */
.reveal * { display: none; } /* class="reveal" */
.reveal *.handle { display: block;} /* class="handle" */
</style>
<script>
// ,
window.onload = function() {
// "reveal"
var elements = document.getElementsByClassName("reveal");
for(var i = 0; i < elements.length; i++) { // ...
var elt = elements[i];
// "handle"
var title = elt.getElementsByClassName("handle")[0];
//
addRevealHandler(title, elt);
}

function addRevealHandler(title, elt) {


title.onclick = function() {
if (elt.className == "reveal") elt.className = "revealed";
else if (elt.className == "revealed") elt.className = "reveal";

336

13. JavaScript -

}
}
};
</script>
</head>
<body>
<div class="reveal">
<h1 class="handle"> , </h1>
<p> . .</p>
</div>
</body>
</html>

, -
, .
JavaScript -.

13.1.1. JavaScript -
JavaScript
Document Element.
, CSS,
,
. ,
HTML (Dynamic HTML, DHTML),
DHTML 15, 16 17.
JavaScript -
.
JavaScript
. JavaScript
; JavaScript ,
:
,
.
,
.

.

13.1.2. JavaScript -
- JavaScript DHTML,
-, ,

, -.
-, , -

. :
(

13.2. JavaScript- HTML

337

) . -
( -)
.
; -
( ) .
API ,
. - API
( 18), ( 20)
(21).
- , -
-,
JavaScript (
, )
. XMLHttpRequest,
HTTP-
. -
. -,
, Ajax-,
, Web 2.0. XMLHttpRequest
18.
HTML5 (
)
-.
,
21 20, ,
(geolocation),
.
, -
. 22.
, JavaScript -
, -. JavaScript
-,
JavaScript. JavaScript,
, -,
JavaScript.1

13.2. JavaScript-
HTML
JavaScript- HTML-
:
1

-, CGI-
HTML -,
JavaScript. -,
.

338

13. JavaScript -

<script> </script>;
, src <script>;
, HTML-,

onclick onmouseover;
URL-,

JavaScript:.

JavaScript. , HTML-
URL javascript:
JavaScript (
).
( <script> src)
. ,
JavaScript (unobtrusive JavaScript), (
HTML) ( JavaScript)
.
, JavaScript HTML-
<script>, src.

13.2.1. <script>
JavaScript- HTML-
<script> </script>:
<script>
// JavaScript-
</script>

XHTML <script>
. JavaScript- < &,
XML-.
XHTML JavaScript- CDATA:
<script><![CDATA[
// JavaScript-
]]></script>

13.2 HTML-,
JavaScript.
, , ,
, JavaScript- HTML
, CSS. ,
13.1
onload.
13.2. JavaScript
<!DOCTYPE html> <!-- HTML5 -->
<html> <!-- -->
<head> <!-- , -->
<title>Digital Clock</title>
<script> // JavaScript

13.2. JavaScript- HTML

339

//
function displayTime() {
var elt = document.getElementById("clock"); // id="clock"
var now = new Date(); //
elt.innerHTML = now.toLocaleTimeString(); //
setTimeout(displayTime, 1000); // 1 .
}
window.onload = displayTime; // .
</script>
<style> /* CSS */
#clock { /* id="clock" */
font: bold 24pt sans; /* */
background: #ddf; /* , - */
padding: 10px; /* */
border: solid black 2px; /* */
border-radius: 10px; /* ( ) */
}
</style>
</head>
<body> <!-- - -->
<h1> </h1> <!-- -->
<span id="clock"></span> <!-- -->
</body>
</html>

13.2.2.
<script> src, URL- ,
JavaScript-. :
<script src="../../scripts/util.js"></script>

JavaScript- .js JavaScript-


<script> HTML-.
<script> src ,
JavaScript- <script>
</script>. , </script> ,
src JavaScript-.
XHTML <script/>.
src
<script> .
<script>
. ,
HTML5
, <script src=""> </script>
- ,
JavaScript.
src :
HTML- , .. Ja
vaScript-, .

340

13. JavaScript -

JavaScript- JavaScript-,

HTML-,
.
, ..
HTML- .
JavaScript
, ,
.
src URL-,
JavaScript- - -
(, ),
-. .

, : Google
, URL-
,
, .
JavaScript Google
-,
,
,
.
: http://code.google.com/apis/ajaxlibs/.
, ,
, ,
, .
, 13.6.2,
JavaScript
. ,
, ,
. ,
: JavaScript-
, ,
, . -
src, ( - ,
) -.

13.2.3.
JavaScript ,
, <script>
JavaScript.
, VBScript Microsoft
( Internet Explorer), type
MIME- :
<script type="text/vbscript">
' // VBScript-
</script>

13.2. JavaScript- HTML

341

type text/JavaScript.
, .
type language
<script>, - -,
:
<script language="javascript">
// JavaScript-...
</script>

language .
- <script> type,
, ,
. , <script>
:
type, ,
. ,
text HTMLElement, script
( , 15). ,

. src
type,
URL.

13.2.4. HTML
JavaScript-, <script>, ,
HTML- -.
JavaScript
JavaScript-, -
- (
). , JavaScript ,
Element ( onclick onmouseover), HTML . (
17.)
, onclick, HTML-
, , Ja
vaScript- HTML-. ,
, , ,
onchange HTML-,
:
<input type="checkbox" name="options" value="giftwrap"
onchange="order.options.giftwrap = this.checked;">

onchange. JavaScript-,
, ,
.
, HTML,
JavaScript-,

342

13. JavaScript -

.
,
. ( ,
HTML- JavaScript,
17.2.2.) HTML-
, ,
, - .
JavaScript-
JavaScript- HTML-. -
HTML-
.

13.2.5. JavaScript URL


JavaScript-
URL- javascript:.
, URL-
JavaScript-,
JavaScript. ,
,
/* */, //.
, URL- javascript:, ,
, .
undefined, , .
URL javascript: ,
URL: href <a>, action <form>
, window.open(). , URL
JavaScript :
<a href="JavaScript:new Date().toLocaleTimeString();">
?
</a>

( Firefox) URL

. , http:,
. ,
, HTML-, ,
, HTML-,
. ( Chrome Safari) URL-
, ,
. URL- :
<a href="JavaScript:alert(new Date().toLocaleTimeString());">
,
</a>

URL-, JavaScript-, , ..
( alert() undefi
ned), , Firefox, .
( URL- javascript: ,

13.2. JavaScript- HTML

343

onclick.
onclick <button> <a>
, .)
, URL- javascript: ,
void undefined:
<a href="javascript:void window.open('about:blank');">Open Window</a>

void URL- , Window.


open(), ( )
:
[object Window]

HTML- , URL- javascript:



HTML-. URL- javascript:
, HTML-.
JavaScript-,
URL- javascript: .
URL- javascript: ,
.

13.2.5.1.
- URL-.
URL- javascript:, -
JavaScript, (bookmarklet).
.
, ;
, .
- ,
, .
URL javascript: <a>.
JavaScript-,
:
<a href='javascript:
var e = "", r = ""; /* */
do {
/* , */
e = prompt(": " + e + "\n" + r + "\n", e);
try { r = ": " + eval(e); } /* */
catch(ex) { r = ex; } /* */
} while(e); /* , */
/* */
void 0; /* */
'>
JavaScript-
</a>

:
, HTML

344

13. JavaScript -

, (//) .
, ,
HTML-, ,
.
, , ,
, , ,
.

. Firefox
.

13.3. JavaScript-
,
JavaScript. ,
JavaScript, - (
, HTML URL- javascript:),
JavaScript, src
<script>.
Window. ,
Document
:
,
JavaScript,
.
- ( <iframe>), JavaScript-
,
,
JavaScript-. ,
, JavaScript-.
, , ,


. Window ,
, 14.8.3.
URL- javascript: -
, ,
.
,
.
JavaScript .

<script> ( , ). (
13.3.1)
.
, ,
, .

13.3. JavaScript-

345


JavaScript-, .
, , -
( HTML-
, , ,
, ) ,
.
( , ..),
,
JavaScript-.
17.
13.3.2.
, URL- javascript:, -,
, .. ,
,
.
,
, load, ,
. JavaScript-
. ,
, ,
onload, load
. onload
, .
JavaScript- ,
- . ,
,
, -.
,
,
JavaScript, ,
, .
JavaScript- 13.3.4.
, JavaScript JavaScript,
.
, .
JavaScript
13.3.3.

13.3.1. ,

JavaScript -,

. , JavaScript-
, .
document.write(). 13.3 ,
JavaScript- 1996.

346

13. JavaScript -

13.3.
<h1> </h1>
<script>
function factorial(n) { //
if (n <= 1) return n;
else return n*factorial(n-1);
}
document.write("<table>"); // HTML-
document.write("<tr><th>n</th><th>n!</th></tr>"); //
for(var i = 1; i <= 10; i++) { // 10
document.write("<tr><td>" + i + "</td><td>" + factorial(i) + "</td></tr>");
}
document.write("</table>"); //
document.write("Generated at " + new Date()); //
</script>

document.write(),
, HTML
, <script> .
document.write()
, - (15.10.2),
. HTML
<script>, , , ,
.
, ,
src, , ,
, , .
, ,
. <script> defer async, (
, ) .
;
<script>. HTML5,
, src,
defer :
<script defer src="deferred.js"></script>
<script async src="async.js"></script>

, defer async, ,
document.write() ,
,
. defer ,
,
. async ,
, .
<script> , ,
, async defer.
,
. ,
, .. .

13.3. JavaScript-

347

async defer
,
: - ,
,
.
,
async,
<script> . load
async(), 13.4.
15.
13.4.
// URL-
function loadasync(url) {
var head = document.getElementsByTagName("head")[0]; // <head>
var s = document.createElement("script"); // <script>
s.src = url; // src
head.appendChild(s); // <script> <head>
}

, loadasync()
, -,
-,
JavaScript-.

13.3.2. ,
JavaScript-, 13.3,
: ,
. .
, ,
. , ,
. -,

, , ,
. . ,
,
.
, ,
onload,
,
.
17,
. , click, change, load,
mouseover, keypress readystatechange,
. , .
, (), ,
: click HTMLButtonElement readystatechange
XMLHttpRequest.

348

13. JavaScript -

, - ,
, ,
.
, .
, HTML-,
JavaScript- HTML .
Java
Script- , :
window.onload = function() { ... };
document.getElementById("button1").onclick = function() { ... };
function handleResponse() { ... }
request.onreadystatechange = handleResponse;

, ,
on,
. ,
: .
.

, ,
, .

, .
, , click,
, , . (IE
-
.) , , ,
,
,
.
, ,
. ,
, <button>, click
. (
) ,
, , ,
click, .

,
,
,
.
, ,
addEventListener(), :
window.addEventListener("load", function() {...}, false);
request.addEventListener("readystatechange", function() {...}, false);

,
. addEventListener()

13.3. JavaScript-

349

, Microsoft
IE9. IE8
, attachEvent():
window.attachEvent("onload", function() {...});

addEventListener() attachEvent() 17.


JavaScript-
, , , .
onerror Window ,
( )
(14.6). , setTimeout() setInterval() (
Window JavaScript
)
. , setTimeout(),
, ,
, , ,
, . setTi
meout() setInterval() 14.1.
13.5 setTimeout(), addEventListener()
attachEvent() onLoad(),
. onLoad() ,
.
13.5. onLoad():
// f, .
// , f .
function onLoad(f) {
if (onLoad.loaded) //
window.setTimeout(f, 0); // f,
else if (window.addEventListener) //
window.addEventListener("load", f, false);
else if (window.attachEvent) // IE8
window.attachEvent("onload", f); //
}
// , , .
onLoad.loaded = false;
// , .
onLoad(function() { onLoad.loaded = true; });

13.3.3.
JavaScript
JavaScript
, JavaScript
. HTML5
Web Workers ( ),
JavaScript-
. ,
JavaScript .

350

13. JavaScript -


: , ,
.
, ,
,
,
.
, -

. :
JavaScript .
,
, ,
.
,
, , .1
,
,
. ,
, ,
.
, ,
, setTimeout() setInterval(),
,
.
HTML5
web worker. Web wor
ker ,

. , web worker,
, ,
web worker,

.
,
JavaScript-.
22.4.

13.3.4.

, JavaScript-
, .
1


,
, ,
.

13.3. JavaScript-

351

Java
Script-.
1. - Document -,
Element
HTML- .
document.readyState loading.
2. HTML <script>,
async / defer,
.
, , (
) , .
document.write()
. ,
.
,
,
.
<script> .
3. <script>,
async,
. ,

. document.write().
<script>, ,
, , .
4. document.readyState
interactive.
5. , defer, ,
.
.
document.write().
6. DOMContentLoaded Document.

. ,
, ,
, .
7. ,
,
.
, document.readyState
complete - load Window.
8.
, , ..
,
. load :
,

352

13. JavaScript -


. DOMContentLoaded load
, IE. document.readyState
,
, , .
defer IE,
. async
,
, 13.4,
. ( ,
, loadasync(),
,
.)
,
- .
.
,
-
, .

.

13.4.
- -,
, -
(
- ,
, IE6), (Microsoft, Mozilla, Apple, Google,
Opera) (Windows, Mac OS,
Linux, iPhone OS, Android).
JavaScript,
.
:

- .
.
- ,
.
,
, -.
-,

, -.
. ,
. -
-

13.4.

353


, .


. ,
. ,
, , .
,
, . , IE8
<canvas>, .
: Microsoft
DOM Level 2 Events (
addEventListener() ).
,
.1

, JavaScript API
.
JavaScript
.
, JavaScript,
,
. ECMA
Script3,
ECMAScript5. ECMAScript3 ECMAScript5
- ,
, , , ,
ECMAScript5.
Java
Script .
-
,
, ,

. .
HTML5
. , ,
,
. -,
:
https://developer.mozilla.org
Mozilla (Mozilla Developer Center)

, IE9
<canvas>, addEventListener().

354

13. JavaScript -

http://msdn.microsoft.com
, Microsoft (Microsoft De
veloper Network)
http://developer.apple.com/safari
Safari (Safari Dev Center)
, Apple (Apple Developer Connection)
http://code.google.com/doctype
Google Doctype
. ,
,
JavaScript.

: ,
.
http://en.wikipedia.org/wiki/Comparison_of_layout_engines_(HTML_5)1
,
API HTML5 .
http://en.wikipedia.org/wiki/Comparison_of_layout_engines_(Document_Object_
Model)
,
DOM.
http://a.deveria.com/caniuse
...
-,
, ,
, .
http://www.quirksmode.org/dom

W3C DOM.
http://webdevout.net/browser-support
,
- .
,
.
JavaScript, .
,
. , .
,
, (
) , .
- ...,
1

: http://ru.wikipedia.org/wiki/
__(HTML5). . .

13.4.

355

(http://a.deveria.com/caniuse): ,
,
IE6 .
,
.


JavaScript ,
ES5 HTML5. ,
,
:
, .
, ,
(
, IE). , ,
, , (
-) :
Internet Explorer8
Firefox3.6
Safari5
Chrome5
Opera10.10
, , ,
: Internet Explorer 9, Firefox4, Safari5, Chrome11 Opera11.
,

. ,
, .

.
2006, Firefox 1.5, IE6,
Safari2 Opera8.5 ( Chrome, Google,
). ,
, ,
, , , .
JavaScript,
(, 22), .
, ,
, ,

, , , ,
(,
Microsoft).

356

13. JavaScript -

13.4.1.

, .
<canvas>,
( 21).
IE ,
. ,
, VML,
<canvas>.
explorercanvas (http://code.google.com/p/explorercanvas)
, : -
excanvas.js JavaScript,
IE , <canvas>.
excanvas.js
. ,
. , ES5 (7.9),
forEach(), map() reduce(), ES3,
,
.
( )
, . ,
IE , API
, addEventListener() .
IE attachEvent(). attachEvent()
, addEventListener(),

, IE.
addEvent()
addEventListener(),
attachEvent(). ,
addEvent() addEventListener() attachEvent().
- -
JavaScript, jQuery ( 19). ,
,
, . jQuery,
,
bind(). jQuery ,
addEventListener() at
tachEvent(). 13.7.

13.4.2.
,
Yahoo!,

.
,

13.4.

357

A,
, C.
A -,
C HTML- ,
JavaScript CSS. ,
A C, X:
. ,
,
-,
.
,
Yahoo!, http://developer.yahoo.com/yui/artic
les/gbs. ,
Yahoo! A C (
). ,
A ,
.

13.4.3.
(
) ,
. , ,
, ,
,
.
,
,
, .
,
. , 17 ,
, :
if (element.addEventListener) { // W3C
element.addEventListener("keydown", handler, false);
element.addEventListener("keypress", handler, false);
}
else if (element.attachEvent) { // IE
element.attachEvent("onkeydown", handler);
element.attachEvent("onkeypress", handler);
}
else { //
element.onkeydown = element.onkeypress = handler;
}

, , ,
.
, ,
,
. ,

358

13. JavaScript -

, . Microsoft
addEventListener(), W3C
,
, addEventListener()
.

13.4.4.
Microsoft IE6,
CSS,
IE5. , .
, CSS, CSS.
,
IE4 IE5.
DOCTYPE HTML-. , DOCTYPE
,
IE5, .
(, ,
)
. , HTML5 (<!DOCT YPE
html>), .

. IE - ,
,
HTML5.
, HTML- CSS-.
JavaScript
, .
document.compatMode.
CSS1Compat, .
BackCompat ( undefined,
), .
compatMode, HTML5.
compatMode .
15.8 ,
.

13.4.5.

. ,
, , , W3C
IE. ,
,
.
,
,
( ).

13.4.

359

Navigator,
14. ,
, (browser sniffer)
(client sniffer).
14.3.
, Netscape IE
.
,
, .
,
, -
, User-Agent, ,
JavaScript- .

13.4.6. Internet Explorer


, ,
,
IE.
IE
. IE
( IE5) JavaScript-,
.
,
HTML. , ,
.
<!--[if IE 6]>
HTML-.
IE6.
<![endif]-->
<!--[if lte IE 7]>
IE 5, 6, 7 .
lte "less than or equal" ( ). "lt",
"gt" "gte".
<![endif]-->
<!--[if !IE]> <-->
HTML-, IE
- , .
<!--> <![endif]-->
, .

excanvas.js,
, <canvas> Internet Exp
lorer. , -
IE ( IE),
, :
<!--[if IE]><script src="excanvas.js"></script><![endif]-->

360

13. JavaScript -

JavaScript IE.
, C/C++,
#ifdef/#endif. JavaScript- IE
/*@cc_on @*/. (
cc cc_on condition compilation, ..
.) ,
IE:
/*@cc_on
@if (@_jscript)
// JS-, IE .
alert("In IE");
@end
@*/

@if, @else
@end, ,
JavaScript IE .

@if (@_jscript). JScript Java
Script, Microsoft, @_jscript IE
true.
JavaScript-
, IE,
:
/*@cc_on
@if (@_jscript)
// ,
// JavaScript-.
// IE , - .
alert(' Internet Explorer');
@else*/
// JavaScript-,
// - IE.
// , IE.
alert(' Internet Explorer');
/*@end
@*/

13.5.

, JavaScript-
. JavaScript-
: JavaScript-,

.

, , , ,
.

13.6.

361

JavaScript-, , Ja
vaScript . ,
JavaScript- ,

. ( , Java
Script .) JavaScript
, .
JavaScript , -, Java
Script-, ( ),
JavaScript .
,
, ( )
, .
, ,
, . -
-
,
JavaScript-. 17, ,
, onmouseover onmousedown, JavaScript
, ,
onfocus onchange.
, .
- ,
.
-,
, WAI-ARIA (Web Accessibility
Initiative Accessible Rich Internet Applications) http://www.w3.org/WAI/intro/aria.

13.6.
JavaScript - ,
- JavaScript-.
,
:

, -.

,
, .
, JavaScript
.

,
.
,
.
, HTML5,

362

13. JavaScript -

( )
, Java
Script, ( ) .
JavaScript
, , -, .

13.6.1. JavaScript
,
. ,
JavaScript
.
JavaScript . (
22.6.5 , JavaScript ,
, 22.7
, JavaScript
.)
JavaScript
. JavaScript
HTTP ( 18). ,
HTML5, WebSockets,
, ,
.
. JavaScript
.

.
:
JavaScript- , - ,
,
,
,
.
JavaScript- , ,
.
value HTML- FileUpload
. ,

(, ).
,
, .

, .
, (
, ) .
(same-origin policy)
.

13.6.

363

, ,
JavaScript.
. ,

.

13.6.2.
,
, -,
JavaScript-.
, - <iframe>
.
JavaScript-
. ,
, (,
JavaScript ,
14.8).
,
URL-, . ,
-, . ,
, .
, , http:,
, https:,
-.
,
:
, . , ,
A, ( src <script>) , B.
, B
.
B,
.
C ( A),

.

, ,
, , Document.
, ,
, , .
, ,
. ,
HTTP XMLHttpRequest (
18). JavaScript-,
, HTTP-, -,
, .

364

13. JavaScript -

,
.
(, ,
) ,

.
.
.

13.6.2.1.


. ,
.

-, . ,
home.example.com
, developer.example.com, orders.
example.com catalog.
example.com. -
domain Document. domain
, .
,
. , domain
home.example.com, examp
le.com, home.example ample.com. ,
domain , , ,
com .
( ) ,
domain,
, .
, , orders.
example.com catalog.example.com, document.domain
example.com,
.

Cross-Origin Resource Sharing (http://
www.w3.org/TR/cors/). HTTP
Origin: Access-Control-Allow-Origin.

, ,
, . ,
Firefox3.5 Safari4, ,
HTTP- XML
HttpRequest, -
.

13.6.

365

,
(cross-document messaging),

. postMessage() Window
(
onmessage) . -
,
,
. API
22.3.

13.6.3.
ActiveX
JavaScript
,
,
, .
JavaScript-
, ActiveX (IE)
( ).
, Flash Java,
.
,
ActiveX . Java,
, .
Java ,
, ;
. :
,
, .
Java Flash, ,

JavaScript. ActiveX .
IE
ActiveX,
Windows .

13.6.4.
(cross-site scripting), XSS,
, HTML-
-. XSS-
-,
. , JavaScript-,
XSS- .
- XSS-,
,
HTML-.

366

13. JavaScript -

-, Ja
vaScript-, :
<script>
var name = decodeURIComponent(window.location.search.substring(1)) || "";
document.write(", " + name);
</script>

window.location.search.substring,
,
?. document.write()
. ,
- URL-:
http://www.example.com/greet.html?name=

, . ,
URL-:
http://www.example.com/greet.html?name=%3Cscript%3Ealert('')%3C/script%3E

URL-
( %3C %3E )!
,
. :
http://siteA/greet.html?name=%3Cscript src=siteB/evil.js%3E%3C/script%3E

,
. B ( C)
( ) A,
B. evil.js B,
A ,
A.
( ,
).
A. ,
cookies, A (,
),
B.
B.
XSS- HTML ,
.
greet.html,
, , <script>:
name = name.replace(/</g, "&lt;").replace(/>/g, "&gt;");

, ,
HTML,
HTML-, . IE8
toStaticHTML(), <script> (
) HTML.

13.7.

367

toStaticHTML() ,
HTML
JavaScript.
HTML5
sandbox <iframe>. ,

, , .
,
.
,
. ,
.
CERT Advisory: http://www.cert.org/advi
sories/CA-2000-02.html.

13.6.5.


, .
- JavaScript-
, alert(),

.
,
,
.
setInter
val(), , ,
. -
.
, .. !

13.7.
- -
.
, ,
,
API -: - ,

.
,
. ,
,
, .

368

13. JavaScript -

19 jQuery
. jQuery ,
, 19,
,
.
jQuery JavaScript
, .
:
Prototype
jQuery, Prototype (http://prototypejs.org)
DOM Ajax
.
Scriptaculous (http://script.aculo.us/),
.
Dojo
Dojo (http://dojotoolkit.org) ,
.
, ,
.
YUI
YUI (http://developer.yahoo.com/yui/) ,
Yahoo! -.
Dojo, ,
DOM, .. ,
YUI 2 YUI 3.
Closure
Closure (http://code.google.com/closure/library/)
, Google -
Gmail, Google Docs .
Closure (http://code.google.com/closure/compi
ler/), .
, -
, Closure
Closure
.
GWT
GWT, Google Web Toolkit (http://code.google.com/webtoolkit/),
.
- Java
Java- JavaScript.
GWT Go
ogle, , Closure.

14
14.

Window

13 Window ,
JavaScript: Window
JavaScript-.
Window.
API, ,
Window.
:
14.1 , setTimeout() setIn
terval()
.
14.2 , location,
URL- .
14.3 history ,
.
14.4 , navigator

screen .
14.5 ,
, alert(), confirm() prompt(),
HTML showModalDialog().
14.6 , onerror,
.
14.7 , HTML-
Window.
14.8 ,
JavaScript-,
.

370

14. Window

14.1.
setTimeout() setInterval() ,

. JavaScript,
Window,
, .
setTimeout() Window
. setTimeout() ,
clearTimeout(),
.
setInterval() setTimeout(), ,

:
setInterval(updateClock, 60000); // updateClock() 60 .

setTimeout(), setInterval() ,
clearInterval(),
.
14.1 ,
,

. setTimeout(), setIn
terval() clearInterval().
14.1.
/*
* f() .
* start , f()
* interval start+end .
* interval , end , f
* . , interval end,
* f , start .
* f, ,
* start 0. , invoke()
* : .
*/
function invoke(f, start, interval, end) {
if (!start) start = 0; // 0
if (arguments.length <= 2) //
setTimeout(f, start); // 1 start .
else { //
setTimeout(repeat, start); // start
function repeat() { //
var h = setInterval(f, interval); // f interval .
// end , end
if (end) setTimeout(function() { clearInterval(h); }, end);
}
}
}

14.2.

371

setTimeout()
setInterval() .
( eval())
. HTML5 ( , IE)
setTimeout() setInterval()
. ,
.
IE, .
setTimeout() 0 ,
, ,
.. .

14.2.
location Window Location,
URL- , ,
.
location Document Location:
window.location === document.location //

, Document URL,
URL .
( #table-of-contents)
Location , , docu
ment.URL .

14.2.1. URL
location Location URL , . href
Location , URL-.
toString() Location href,
, toString(),
location.href location.
, protocol, host, hostname, port, pathname,
search hash, URL-.
URL Link (
<a> <area> HTML-).
Location Link .
hash search Location .
hash URL, :
(#) . search
URL-, ,
, . URL-
. URL-
URL-.
, ,

372

14. Window

,
, JavaScript-. 14.2
urlArgs(),
search URL-. decodeURICompo
nent(), JavaScript. ( Glo
bal .)
14.2. search URL-
/*
* URL-
* / .
* . :
*
* var args = urlArgs(); // URL
* var q = args.q || ""; // , ,
//
* var n = args.n ? parseInt(args.n) : 10;
*/
function urlArgs() {
var args = {}; //
var query = location.search.substring(1); // '?'
var pairs = query.split("&"); //
for(var i = 0; i < pairs.length; i++) { //
var pos = pairs[i].indexOf('='); // /
if (pos == -1) continue; // -
var name = pairs[i].substring(0,pos); //
var value = pairs[i].substring(pos+1); //
value = decodeURIComponent(value); //
args[name] = value; //
}
return args; //
}

14.2.2.
assign() Location
URL-. replace() ,

. ,
replace(), assign().
Back ()
. location.replace()
-
HTML, ,
,
:
// XMLHttpRequest,
// , .
if (!XMLHttpRequest) location.replace("staticpage.html");

14.3.

373

, URL- ,
replace(), . URL-
, , ,
.
assign() replace() Location reload(),
.

, URL- location:
location = "http://www.oreilly.com"; // , !

location URL-.
URL:
location = "page2.html"; //

URL-,
,
, . #top
: top,
:
location = "#top"; //

URL Location ,
URL- location
(, hash,
):
location.search = "?page=" + (pagenum+1); //

14.3.
history Window History .
History
. length History
, , ,
URL-. (
-.)
back() forward() Back () Forward ()
:
. , go(),
, (
) ( ) .
history.go(-2); // 2 ,
// Back ()

( <iframe>
14.8.2),
. history.back() (
) ,
, , .

374

14. Window

-
( 15 18).
, ,
Back Forward
. HTML5
, 22.2.
HTML5
. ,
, ,
, Back,
, ,

.
<iframe>,
.
, ,
open() write() Document (15.10.2).
,
. Back,
. HTML5
, , ,
Back,
setInterval() (14.1) 23
.
,
, .
JavaScript . ,
jQuery history.
. ,
RSH (Really Simple History
). http://code.google.com/p/reallysimplehistory/.
22.2 , HTML5.

14.4.
-,
, , .
navigator screen Window.
, , Navigator Screen,
,
.

14.4.1. Navigator
navigator Window Navigator,
. Navigator
Netscape Navigator,
. ( , IE clientInformation

14.4.

375

navigator. ,
.)
Navigator
Internet Explorer Netscape.
, ..

.
(13.4.3).
- ,
(,
).

. ,
. Navigator
, ,
:
appName
-. IE Microsoft Internet Explorer. Firefox
Netscape.

Netscape.
appVersion
,
.
4.0 5.0,
.
appVersion ,
, .
userAgent
, http- USER-AGENT.
, appVersion,
.
appVersion, .
,
.
platform
, (, ,
), .
Navigator
.
, ,
, navigator.appName. ,
,
- Netscape
appName.

376

14. Window

appVersion,
navigator.userAgent,
, . 14.3 ,
( jQuery) navigator.
userAgent .
14.3. navigator.userAgent
// browser.name browser.version,
// . jQuery 1.4.1.
// , name version, ,
// .
// :
//
// "webkit": Safari Chrome; version WebKit
// "opera": Opera; version
// "mozilla": Firefox , gecko;
// version Gecko
// "msie": IE; version
//
// , Firefox3.6 : {name: "mozilla", version: "1.9.2"}
var browser = (function() {
var s = navigator.userAgent.toLowerCase();
var match = /(webkit)[ \/]([\w.]+)/.exec(s) ||
/(opera)(?:.*version)?[ \/]([\w.]+)/.exec(s) ||
/(msie) ([\w.]+)/.exec(s) ||
!/compatible/.test(s) && /(mozilla)(?:.*? rv:([\w.]+))?/.exec(s) ||
[];
return { name: match[1] || "", version: match[2] || "0" };
}());

,
Navigator .
:
onLine
navigator.onLine ( ) ,
.
( , 20),
.
geolocation
Geolocation, API
. 22.1.
javaEnabled()
, true,
Java-.
cookiesEnabled()
, true,
cookies. cookies
, .

14.5.

377

14.4.2. Screen
screen Window Screen,

. width height .
availWidth availHeight ;
, ,
. colorDepth ,
. 16, 24 32.
window.screen Screen, ,
, . Screen
, , -
, .
, ,
.

14.5.
Window .
alert() ,
. confirm() OK
Cancel () . prompt()
, .
:
do {
var name = prompt(" "); //
var correct = confirm(" '" + name + "'.\n" + // . .
" , , " +
" , .");
} while(!correct)
alert(", " + name); //

alert(), confirm() prompt() ,


, .
, , ,
, ,
. ,
, . JavaScript- alert()
, .
, , alert(), confirm() prompt()
, .
, .
confirm() prompt() , ..
, .1
, , ,
, , ,
1

. . . .

378

14. Window

, .
alert()
,
.
Window.alert, Window.confirm Window.prompt .
alert(), confirm() prompt() Window
, showModalDialog(), ,
HTML,
. showModalDialog()
. URL,
HTML- .
( ),
, window.dialogArguments.
/,
, , ,
.
dialogwidth dialogheight,
,
resizable=yes.
, , , showModalDialog()
, .
window.returnValue .
HTML OK,
returnValue window.close() (14.8.1.1).
14.4 HTML showMo
dalDialog(). showModal
Dialog(), .14.1 , .
, , ,
showModalDialog() ,
HTML.

.14.1. , showModalDialog()

14.6.

379

14.4. HTML- showModalDialog()


<!- HTML-. showModalDialog()
window.dialogArguments .
- , .
- .
Okay.
:
var p = showModalDialog("multiprompt.html",
["Enter 3D point coordinates", "x", "y", "z"],
"dialogwidth:400; dialogheight:300; resizable:yes");
-->
<form>
<fieldset id="fields"></fieldset> <!-- , -->
<div style="text-align:center"> <!-- -->
<button onclick="okay()">Okay</button> <!-- -->
<!-- -->
<button onclick="cancel()">Cancel</button> <!-- , -->
<!-- -->
</div>
<script>
// HTML fieldset
var args = dialogArguments;
var text = "<legend>" + args[0] + "</legend>";
for(var i = 1; i < args.length; i++)
text += "<label>" + args[i] + ": <input id='f" + i + "'></label><br>";
document.getElementById("fields").innerHTML = text;
//
function cancel() { window.close(); }
// ,
//
function okay() {
window.returnValue = []; //
for(var i = 1; i < args.length; i++) //
window.returnValue[i-1] = document.getElementById("f" + i).value;
window.close(); // . showModalDialog() .
}
</script>
</form>

14.6.
onerror Window ,
,
Java
Script. ,
,
JavaScript: .
, onerror Window
, ,

380

14. Window

. ( JavaScript
onerror, ,
,
.) window.onerror
, . ,
URL- JavaScript-, .
, .
,
onerror. onerror true,
, ;
, .
, Firefox
true, , .
onerror JavaScript,
try/catch .
.
,
, :
// , 3
window.onerror = function(msg, url, line) {
if (onerror.num++ < onerror.max) {
alert(": " + msg + "\n" + url + ":" + line);
return true;
}
}
onerror.max = 3;
onerror.num = 0;

14.7.
HTML- id
Window ,
, Window ,
id, HTMLEle
ment, .
, Window ,
JavaScript.
, , id HTML-
, . , ,
<button id="okay"/>,
okay.
, , Window
. id, histo
ry, location navigator, ,
, . , HTML id, x
x,

14.7.

381

, .
,
,
. ,
,
.
15.2 , document.getElementById()
HTML- id.
:
var ui = ["input","prompt","heading"]; //
ui.forEach(function(id) { // id
ui[id] = document.getElementById(id); //
});

ui.input, ui.prompt ui.heading


. ui.input ui.heading
input heading. , 14.5,
Window prompt(),
prompt ui.prompt.

-.
-
,
Window,
,
. ,
document.getElementById(). ,
:
var $ = function(id) { return document.getElementById(id); };
ui.prompt = $("prompt");

$,
, . (19 ,
$ jQuery
, ,
, , class .)
HTML- id
, id Window.
HTML- , name:
<a> <applet> <area> <embed> <form> <frame> <frameset> <iframe> <img> <object>

id
: id.
name. ,
, name (,
name, id ),
,
, .

382

14. Window

<iframe> name id . ,
, Element,
, Window, ,
<iframe>. 14.8.2.

14.8.
- .
.
Window, . ,
,
,
Window
. , ,
, -
. ,
Window, .
.
,
( ,
, 13.6.2).
14.8.1.
HTML- ,
<iframe>. <iframe> ,
Window.
<frameset> <frame>
, <frame> Window.
, , ( <iframe>)
JavaScript :

Window. ,
. ,
, ,

.
14.8.2.
JavaScript Window
,
JavaScript. JavaScript, ,
, ,
, , .
14.8.3. ,

, HTML5
, ,
.
22.3.

14.8.

383

14.8.1.
- ( ,
) open() Window. Window.open()
URL-
Window, .
:
open() URL- , .
( ),
URL about:blank.
open() .
(
), .
. ,
_blank, .. .
,
, -
: ,
( HTML5). ,
,
, ,
( ,
). , , ,
.
_top (
) _parent (
).


,
open(), ,
HTML- target <a> <form>,
( ),
. target
_blank, _parent _top,
,
.
, , name Window.
,
. Window.open() ( _blank),
, , ,
name. <iframe> name,
Window, ,
name name.

384

14. Window

open() ,

. ,
: , ,
.. , ,
. ,
. (
, , .)
, , ,
, ,
:
var w = window.open("smallwin.html", "smallwin",
"width=400,height=350,status=yes,resizable=yes");

, HTML5 ,
. ,
, Window.open()
. , , ,
. ,
,
, . , ,

; ,
.
open() ,
. ,
, URL-, ,
(true)
(false). , false.
, open(), Window,
. JavaScript-
, Window ,
:
var w = window.open(); //
w.alert(" http://example.com"); // alert()
w.location = "http://example.com"; // - location

, window.open(), opener
Window , . opener
null:
w.opener !== null; // w, open()
w.open().opener === w; // w

Window.open()
,
. ,
- .
open() ,

14.8.

385

, .
, ,
( ) , .
Java
Script .

14.8.1.1.
open()
close(). Window ,
:
w.close();

JavaScript-, , :
window.close();

window
close() Window close()
Document , close()
.

, JavaScript-.
,
( ) .
close() Window, ,
, : (
<iframe> ).
Window
. - ,
closed. ,
true, document null,
.

14.8.2.
, open() Window Window,
opener . ,
,
. . ,
,
, .
,
window self.
Window parent:
parent.history.back();

Window, ,
, parent :
parent == self; //

386

14. Window

,
, : parent.parent.
top:
top
. Window ,
top . ,
, top
parent.
parent top
.
. <iframe>.
Element, <iframe>, ,
, . ,
<iframe id="f1">. Element,
iframe :
var iframeElement = document.getElementById("f1");

<iframe> contentWindow,
Window , Window
:
var childFrame = document.getElementById("f1").contentWindow;

Window,
, Element <iframe>, ,
frameElement Window. Window,
, , null frameElement:
var elt = document.getElementById("f1");
var win = elt.contentWindow;
win.frameElement === elt //
window.frameElement === null //

, ,
getElementById() contentWindow. Window
frames, ,
. frames , ,
.

frames[0].
frames[1].frames[2]. ,
, , parent.frames[1].
, frames[] Window,
<iframe>.
<iframe> name id,
, . ,
f1 frames["f1"]
frames.f1.
14.7 , <iframe>
Window

14.8.

387

<iframe> , :

Window, Element. , fl
f1 frames.f1. ,
HTML5 , frames, window self,
Window, . ,
, window[0],
, window.length length.
frames window
. ,
frame==window, ,
,
, .
name id <iframe> ,
JavaScript-.
name,
name Window, . , ,
target
window.open() .

14.8.3. JavaScript
Window,
JavaScript-.
(
),
.
- <iframe>, A B,
, ,
, .
A i:
var i = 3;

, ..
Window. A
window:
window.i

B Window
A, :
parent.A.i = 4; // A

, function, ,
, var. JavaScript- B
f, B,
B f f().
A f Window B:
parent.B.f(); // , B

388

14. Window

A ,
A, :
var f = parent.B.f;

A f() ,
B.
,
.
, , , .
, f ,
B,
A.
, ,
(. 9) -
-, .
, , A B, Set 9.6.
Set,
:
var s = new Set();

Set(),
:
var s = new parent.Set();


-:
var Set = top.Set();
var s = new Set();

, ,
Set, Date RegExp, .
,
-. ,
String() String.prototype. ,
JavaScript-
String, String.prototype ,
,
, .
, Window -,
, instanceof .
, instanceof false
B String() A. 7.10
.

14.8.

389

WindowProxy
, JavaScript Window
.
, . , -
, Java
Script, .

Window, ,
.
, JavaScript ,
. ,

.
,
. , Window,

. ,
Window,
.
HTML5 WindowProxy,
Window.

, , .
, .

.
, window, self, top, parent frames
. window.open()
. this
, .1

ES3 ES5,

JavaScript.

15
15.

JavaScript ,
HTML- -. JavaScript.
, .
13 14 , , -
Window. Window document,
Document. Document
. Document .
API,
(Document Object Model, DOM),
.
DOM,
:
.
,
, , .
.
.
, , .
HTML-.

, referrer, write() ,
.

15.1. DOM
(Document Object Model, DOM)
,

391

15.1. DOM

HTML- XML-.
(API) DOM ,
,
, , HTML- XML-
DOM.
HTML- , ,
<body> <p>, , . HTML-
, HTML-.
HTML-:
<html>
<head>
<title>Sample Document</title>
</head>
<body>
<h1>An HTML Document</h1>
<p>This is a <i>simple</i> document.
</html>

DOM- .15.1.
,
, ,
. ,
, . ,
,
. ,
, . ,
, . ,
, , .
Document
<html>

<head>

<body>

<title>
"Sample Document"

<p>

<h1>
"An HTML Document"
"This is a"

<i>
"simple"

.15.1. HTML-

"document"

392

15.

.15.1 ,
Node. Node
, , ,
Node . ,
.
Document, . ,
HTML-, Element, , ,
Text. Document, Element Text Node,
. Document Element
DOM,
.
Node , .15.2.
Document
Element, HTMLDocument HTMLElement. Document HTML XML-, Element .
HTMLDocument HTMLElement HTML-
. Document
Element, HTML-.
: HTMLDocument HTMLEle
ment Document Element.
HTMLHeadElement

Document

HTMLDocument
Text

CharacterData
Comment
Node
Element
Attr

HTMLElement

HTMLBodyElement
HTMLTitleElement
HTMLParagraphElement
HTMLInputElement
HTMLTableElement
. . . etc.

.15.2.

. 15.2
HTMLElement, HTML-.
JavaScript-, HTML-
(15.4.1).
,
HTML.

.

15.2.

393

, , .15.2 ,
. Comment HTML-
XML-.
, Text,
. CharacterData, Text Comment,
, . Attr
XML- HTML-, ,
Element ,
, /, . DocumentFragment
( ) ,
: ,
. DocumentFragment
,
15.6.4. DOM
, , ,
XML.

15.2.
JavaScript
.
document,
Document. , -
, - , ,
Element, . DOM
.
:
id;
name;
;
CSS;
CSS.
.

15.2.1. id
HTML- id.

id.
id getElementById()
Document. 13 14:
var section1 = document.getElementById("section1");

.
-
, id
.

394

15.

id,
getElements(),
15.1.
15.1. id
/**
* .
* id ,
* document.getElementById().
* , id
* Element. - id
* , Error.
*/
function getElements(/* id...*/) {
var elements = {}; //
for(var i = 0; i < arguments.length; i++) { //
var id = arguments[i]; // - id
var elt = document.getElementById(id); //
if (elt == null) // ,
throw new Error("No element with id: " + id); //
elements[id] = elt; // id
}
return elements; // id
}

Internet Explorer IE8 getElementById()


id , ,
, name.

15.2.2. name
HTML- name
, ,
. id, name
. , id, name
: ,
. ,
id, name HTML, , <iframe> <img>.
HTML-, name,
getElementsByName() Document:
var radiobuttons = document.getElementsByName("favorite_color");

getElementsByName() Document, HTMLDocu


ment, HTML- XML-
. NodeList, ,
Element. IE getElementsByName()
, id
. ,

name id.

15.2.

395

14.7, name HTML-



Window. Document. name
<form>, <img>, <iframe>, <applet>, <embed> <object> ( <object>,
)
Document,
( ,
).
,
.
, NodeList,
. 14.7, <iframe>
: Element,
Window, .
,
Document:
// Element <form name="shipping_address">
var form = document.shipping_address;

,
, 14.7,
.
, , getEle
mentsByName().

15.2.3.
getElementsByTagName() Document HTML-
XML- ( ). ,
, , Element
<span> , :
var spans = document.getElementsByTagName("span");

getElementsByName(), getElementsByTagName() No
deList. ( NodeList , .)
NodeList ,
, .. <p> :
var firstpara = document.getElementsByTagName("p")[0];

HTML- , getElements
ByTagName() HTML-,
. spans, , ,
<span>, <SPAN>.
NodeList, ,
getElementsByTagName() *.
, Element getElementsByTagName().
, Document,
, ,

396

15.

. <span>
<p> :
var firstpara = document.getElementsByTagName("p")[0];
var firstParaSpans = firstpara.getElementsByTagName("span");

HTMLDocument
. images, forms links,
, , ,
, <img>, <form> <a> ( <a>,
href). HTMLCollection,
NodeList,
id name. ,
<form> :
document.shipping_address

document.forms , name
( id), :
document.forms.shipping_address;

HTMLDocument - embeds plugins,


HTMLCollection <embed>. anchors
, <a>,
name, href. scripts
HTML5 HTMLCollection <script>,
.
, HTMLDocument ,
, . document.body
<body> HTML-, document.head <head>.
:
<head> <body>, . document
Element Document . HTML-
<html>.

NodeList HTMLCollection
getElementsByName() getElementsByTagName()
NodeList, , document.images document.forms,
HTMLCollection.
, ,
(7.11). length
( ) .
NodeList HTMLCollection
, :
for(var i = 0; i < document.images.length; i++) // .
document.images[i].style.display = "none"; // ... .

15.2.

397

NodeList HTMLCollection
Array, :
var content = Array.prototype.map.call(
document.getElementsByTagName("p"),
function(e) { return e.innerHTML; });

HTMLCollection
, .
, NodeList HTMLCollection,
:
.
.
, NodeList HTMLCollection,
, , Java
Script. item().
. JavaScript
,
. HTMLCollection
namedItem(), ,
JavaScript
.
NodeList
HTMLCollection ,
, , ,
, .
getElementsByTagName('div') ,
<div>, NodeList, length 0.
<div>,
NodeList, length 1.
NodeList HTMLCollection
.
NodeList,
NodeList:
var snapshot = Array.prototype.slice.call(nodelist, 0);

15.2.4. CSS
HTML- class
, .
: , class
, . class
JavaScript, HTML-
class JavaScript className.

398

15.

class CSS,
,
16. , HTML5
getElementsByClassName(),
class.
getElementsByTagName(), getElementsByClassName()
HTML-, HTML-,
NodeList, ,
. getElementsByClassName()
,
, .
, class .
. ,
class, getElementsByClassName()
, .
getElementsByClassName():
// "warning" class
var warnings = document.getElementsByClassName("warning");
// "log" "error"
// "fatal" class
var log = document.getElementById("log");
var fatal = log.getElementsByClassName("fatal error");

HTML-
, <!DOC
TYPE> .
, ,
class CSS
. getElementsByClassName()
, .
, .
.
getElementsByClassName()
, IE8 .
IE8 querySelectorAll(), ,
getElementsByClassName().

15.2.5.
CSS
CSS
, ,
. CSS
1,
. id class:
1

CSS3 http://www.w3.org/TR/css3-selec
tors/.

15.2.

399

#nav // id="nav"
div // <div>
.warning // "warning" class

, :
p[lang="fr"] // : <p lang="fr">
*[name="x"] // name="x"

:
span.fatal.error // <span> "fatal" "error"
span[lang="fr"].warning //


:
#log span // <span>, id="log"
#log>span // <span>, id="log"
body>h1:first-child // <h1>, <body>


:
div, #log // <div> id="log"

, CSS ,
: id name, .
CSS3, W3C,
Selectors API (API ), JavaScript
, .1
API querySelectorAll() Document.
CSS NodeList,
, .
, NodeList,
querySelectorAll(), : ,
,
. ,
, querySelectorAll() NodeList.
querySelectorAll() , .
querySelectorAll()
querySelector(), querySelectorAll(), ,
( )
null, .
Elements ( DocumentFragment,
15.6.4).
,
, ,
.
, ,
, .
1

Selectors API HTML5, .


http://www.w3.org/TR/selectors-api/.

400

15.

, CSS :first-line
:first-letter. CSS ,
. ,
querySelectorAll() querySelector(). ,
:link :visited,

.
querySelector() querySelectorAll() .
,
CSS3:
,
. , IE, CSS3.
IE7 8 CSS2. (, IE9
CSS3.)
querySelectorAll() :
,
JavaScript
. , CSS ,
querySelectorAll().
jQuery (19)
. - jQuery
,
querySelectorAll(), $().
, jQuery
CSS,
Sizzle, Dojo
.1 , Sizzle
( , Sizzle), ,
,
, .

15.2.6. document.all[]
, DOM , IE4
document.all[], ( Text)
. document.all[]
, getElementById() getElementsByTagName(),
.
,
, :
document.all[0] //
document.all["navbar"] //
//
document.all.navbar //
document.all.tags("div") //
document.all.tags("p")[0] //
1


( ) "navbar"
id name

<div>
<p>

Sizzle http://sizzlejs.com.

15.3.

401

15.3.


(, , ). Docu
ment Node, . 15.1.
Node , ,
15.3.1.
, Element.
( )
15.3.2.

15.3.1.
Document, Element Text,
, Node. Node
:
parentNode
null , ,
Document.
childNodes
, (NodeList),
.
firstChild, lastChild
null,
.
nextSibling, previousSibling
. ,
.
.
.
nodeType
. Document 9 .
Element 1. Text 3.
Comments 8 DocumentFragment 11.
nodeValue
Text Comment.
nodeName
Element,
.
Node
Document, :
document.childNodes[0].childNodes[1]
document.firstChild.firstChild.nextSibling

402

15.

, :
<html><head><title>Test</title></head><body>Hello World!</body></html>

<body>.
nodeType 1 nodeName BODY.
, ,
. ,
<html> <head>,
( Text)
, <head>, <body>.

15.3.2.
,
( ),
, Ele
ment, Text Comment, .
children
Element. childNodes, NodeList.
, childNodes, children
Element. children ,
. IE ,
.
, , Firefox3.5.
, Text Comment . ,
Node.parentNode Text
Comment. parentNode Element
Element Document DocumentFragment.

Element,
Node:
firstElementChild, lastElementChild
firstChild lastChild, .
nextElementSibling, previousElementSibling
nextSibling previousSibling,
.
childElementCount
. ,
children.length.

, IE.1

,
, 15.2.
1

http://www.w3.org/TR/ElementTraversal.

15.3.

403

15.2.
/**
* n- e null,
* Element
* (, Document DocumentFragment).
* n 0, e.
* n 1 ( ),
* .
* n 2, ..
*/
function parent(e, n) {
if (n === undefined) n = 1;
while(n-- && e) e = e.parentNode;
if (!e || e.nodeType !== 1) return null;
return e;
}
/**
* n- e.
* n ,
* n- .
* n ,
* n- .
* n , e.
*/
function sibling(e,n) {
while(e && n !== 0) { // e ,
if (n > 0) { //
if (e.nextElementSibling) e = e.nextElementSibling;
else {
for(e=e.nextSibling; e && e.nodeType !== 1; e=e.nextSibling)
/* */ ;
}
n--;
}
else { //
if (e.previousElementSibing) e = e.previousElementSibling;
else {
for(e=e.previousSibling;e&&e.nodeType!==1;e=e.previousSibling)
/* */ ;
}
n++;
}
}
return e;
}
/**
* n- e null,
* .
* n ,
* . 0 ,
* -1 , -2 ..
*/

404

15.

function child(e, n) {
if (e.children) { //
if (n < 0) n += e.children.length; //
//
if (n < 0) return null; //
//
return e.children[n]; //
}

children


,
,

// e children,
// , ,
// , .
if (n >= 0) { // n - : ,
// e
if (e.firstElementChild) e = e.firstElementChild;
else {
for(e = e.firstChild; e && e.nodeType !== 1; e = e.nextSibling)
/* */;
}
return sibling(e, n); // n-
}
else { // n - : ,
if (e.lastElementChild) e = e.lastElementChild;
else {
for(e = e.lastChild; e && e.nodeType !== 1; e=e.previousSibling)
/* */;
}
return sibling(e, n+1); // +1, -1
// 0
}
}1


( IE8 ) DOM
, , Element HTMLDocument1, ,
String Array. (
Element, ),
-, :
Element.prototype.next = function() {
if (this.nextElementSibling) return this.nextElementSibling;
var sib = this.nextSibling;
while(sib && sib.nodeType !== 1) sib = sib.nextSibling;
return sib;
};

IE8 Element, HTMLDocument


Text, Node, Document, HTMLElement
HTMLElement.

15.4.

405

, 15.2,
Element ,
IE7.
DOM
, IE, .
, children Element
IE .
, ,
, Firefox3.0:
// Element.children ,
//
// ,
// , "" NodeList
if (!document.documentElement.children) {
Element.prototype.__defineGetter__("children", function() {
var kids = [];
for(var c = this.firstChild; c != null; c = c.nextSibling)
if (c.nodeType === 1) kids.push(c);
return kids;
});
}

__defineGetter__ ( 6.7.1)
,
, .

15.4.
HTML- /,
. , <a>, ,
href.
HTML- HTMLElement,
. , DOM
XML- HTML-
. .

15.4.1. HTML- Element


HTMLElement, HTML-,
, /, HTML-
. HTMLElement
HTTP-, id, title, lang dir, -
, onclick. Element
, . ,
URL- , src HTML
Element, <img>:

406

15.

var image = document.getElementById("myimage");


var imgurl = image.src; // src URL-
image.id === "myimage" // id

<form>,
:
var f = document.forms[0]; // <form>
f.action = "http://www.example.com/submit.php"; // URL .
f.method = "POST"; // HTTP-

HTML ,
JavaScript.
JavaScript,
. , ,
, , , :
defaultChecked tabIndex.
HTML-
JavaScript. , ,
html. , HTML- for ( <label>)
JavaScript htmlFor. HTML-
class, ( )
JavaScript class, :
JavaScript className.
className 16.
, HTML-, .
(, defa
ultChecked maxLength <input>),
, .
Function ( null).
HTML5 ( form <input>
),
Element. , style HTML-
CSSStyleDeclaration, .
16.
,

. , delete.
, .

15.4.2. HTML-
, HTMLElement ,
HTML-. Element
getAttribute() setAttribute(),
HTML-,
XML-:
var image = document.images[0];
var width = parseInt(image.getAttribute("WIDTH"));
image.setAttribute("class", "thumbnail");

15.4.

407


, . -
, . getAttri
bute() , . -,
,
JavaScript. HTML-
.
Element , hasAttribute() remove
Attribute(). ,
.
: ( disabled HTML-)
, .
XML-,
,
, : getAttributeNS(), setAttri
buteNS(), hasAttributeNS() removeAttributeNS().
.
URI-, .

. setAttributeNS(),
,
.

.

15.4.3.
HTML- ,
Java
Script- .
, class. ,
,
. ,
getAttribute()
setAttribute(). .
HTML5 . ,
HTML5, ,
data-,
.
, ,
.
, HTML5 Element dataset.
, ,
data- . dataset.x
data-x.
: data-jquery-test
dataset.jqueryTest.

408

15.

. ,
:
<span class="sparkline" data-ymin="0" data-ymax="10">
1 1 1 2 2 3 4 5 5 4 3 5 6 7 7 4 2 1
</span>

Sparkline , ,
.
, , :
// , Array.map(),
// ES5 ( )
var sparklines = document.getElementsByClassName("sparkline");
for(var i = 0; i < sparklines.length; i++) {
var dataset = sparklines[i].dataset;
var ymin = parseFloat(dataset.ymin);
var ymax = parseFloat(dataset.ymax);
var data = sparklines[i].textContent.split(" ").map(parseFloat);
drawSparkline(sparklines[i], ymin, ymax, data); //
}

dataset
,
:
var sparklines = document.getElementsByClassName("sparkline");
for(var i = 0; i < sparklines.length; i++) {
var elt = sparklines[i];
var ymin = parseFloat(elt.getAttribute("data-ymin"));
var ymin = parseFloat(elt.getAttribute("data-ymax"));
var points = elt.getAttribute("data-points");
var data = elt.textContent.split(" ").map(parseFloat);
drawSparkline(elt, ymin, ymax, data); //
}

, dataset ( ,
) , data- .
dataset
data- .
drawSparkline() ,
21.13 (spark
lines), , <canvas>.

15.4.4. Attr
. Node
attributes. null ,
Element. attributes Element
, , ,
. NodeList, attributes
. ,
, :

15.5.

409

document.body.attributes[0] // <body>
document.body.attributes.bgcolor // bgcolor <body>
document.body.attributes["ONLOAD"] // onload <body>

, attributes,
Attr. Attr Node,
. name
value Attr .

15.5.
. 15.1 :
<p>. :
HTML This is a <i>simple</i> docu
ment.
This is a simple document.
Text, Element,
Text, Text.
, -.
,
HTML,
.

15.5.1. HTML
innerHTML Element
.
-
. (
, innerHTML
HTML-, XML-.)
-
HTML, innerHTML
, .
,
innerHTML += ,

.
innerHTML IE4.
,
HTML5. HTML5 ,
innerHTML Element,
Document, .
, HTML5 outerHTML.
outerHTML HTML
XML, ,
. outerHTML

410

15.

. outerHTML
Element, Document.
outerHTML
, Firefox. (15.5, ,
outerHTML innerHTML.)
, IE
HTML5, insertAdjacentHTML(),
HTML, (adjacent)
. ,
(adjacent)
. : before
begin, afterbegin, beforeend afterend.
, .15.3.
<div id="target"> This is the element content </div>
beforebegin

afterbegin

beforeend afterend

.15.3. insertAdjacentHTML()

insertAdjacentHTML() Firefox.
15.6, ,
insertAdjacentHTML() innerHTML
HTML,
.

15.5.2.

(
, HTML).
textContent
Node:
var para = document.getElementsByTagName("p")[0]; // <p>
var text = para.textContent; // "This is a simple document."
para.textContent = "Hello World!"; //

textContent , IE.
IE innerText. inner
Text IE4 ,
Firefox.
textContent innerText ,
.
( "" JavaScript
) :
/**
* textContent
* innerText .

15.5.

411

* textContent innerText .
*/
function textContent(element, value) {
var content = element.textContent; // textContent ?
if (value === undefined) { // value ,
if (content !== undefined) return content; //
else return element.innerText;
}
else { //
if (content !== undefined) element.textContent = value;
else element.innerText = value;
}
}

textContent
Text, . innerText
textContent. innerText
<script>.

. , , <table>,
<tbody> <tr>, innerText .

<script>
<script> (.. src) text,

. <script> ,
HTML-
. <script>
, -
. type -
( text/x-custom-data), ,
JavaScript.
JavaScript ,
,
text.

15.5.3.

, .
,
. XML-
CDATASection Text
CDATA.
15.3 textContent(),
,

412

15.

-. , , node
Value ( Node) .
15.3. ,
// e,
// . textContent
function textContent(e) {
var child, type, s = ""; // s
for(child = e.firstChild; child != null; child = child.nextSibling) {
type = child.nodeType;
if (type === 3 || type === 4) // Text CDATASection
s += child.nodeValue;
else if (type === 1) // Element
s += textContent(child);
}
return s;
}

nodeValue ,
Text CDATASection. , Text CDATA
Section, CharacterData,
. CharacterData data,
, nodeValue.
Text ,
data:
// -
// n .
function upcase(n) {
if (n.nodeType == 3 || n.nodeTyep == 4) // n - Text CDATA
n.data = n.data.toUpperCase(); //
else //
for(var i = 0; i < n.childNodes.length; i++)
upcase(n.childNodes[i]);
}

CharacterData
, , Text CDATASection.

Element
. ,
.

15.6. ,
, ,
HTML . ,
Element Text,
.
. Document
Element Text, Node ,

15.6. ,

413

.
13.4, :
// URL-
function loadasync(url) {
var head = document.getElementsByTagName("head")[0]; // <head>
var s = document.createElement("script"); // <script>
s.src = url; // src
head.appendChild(s); // <script> <head>
}


, ,
DocumentFragment, .

15.6.1.
, Element
createElement() Document.
: HTML-
XML-.
:
var newnode = document.createTextNode(" ");

, Document ,
createComment(). , createDocumentFrag
ment(), 15.6.4. ,
XML, createEle
mentNS(), URI-
Element.

. cloneNode(),
. true,
,
. , IE, Document
importNode().
, , .
true ,
-.

15.6.2.

Node: appendChild() insertBefore(). appendChild()
Element, ,
, (
lastChild).
insertBefore() appendChild(),
. , ,
.

414

15.

, ,
.
null, insertBefore() , appendChild(),
.

. , appendChild()
insertBefore():
// child parent , n-
function insertAt(parent, child, n) {
if (n < 0 || n > parent.childNodes.length)
throw new Error(" ");
else if (n == parent.childNodes.length) parent.appendChild(child);
else parent.insertBefore(child, parent.childNodes[n]);
}

appendChild() insertBefore() ,
,
;
. 15.4
.
appendChild().
15.4.
// <tbody>
// n- . , .
// .
function sortrows(table, n, comparator) {
var tbody = table.tBodies[0]; // <tbody>;
var rows = tbody.getElementsByTagName("tr"); // tbody
rows = Array.prototype.slice.call(rows,0); //
// n- <td>
rows.sort(function(row1,row2) {
var cell1 = row1.getElementsByTagName("td")[n]; // n-
var cell2 = row2.getElementsByTagName("td")[n]; //
var val1 = cell1.textContent || cell1.innerText; // .
var val2 = cell2.textContent || cell2.innerText; //
if (comparator) return comparator(val1, val2); // !
if (val1 < val2) return -1;
else if (val1 > val2) return 1;
else return 0;
});
// tbody .
// ,
// . <tbody>
// - , <tr>, "" .
for(var i = 0; i < rows.length; i++) tbody.appendChild(rows[i]);
}
// <th> (,
// ) ,
// .

15.6. ,

415

function makeSortable(table) {
var headers = table.getElementsByTagName("th");
for(var i = 0; i < headers.length; i++) {
(function(n) { //
headers[i].onclick = function() { sortrows(table, n); };
}(i)); // i n
}
}

15.6.3.
removeChild() .
: , ,
( child )
.
, . n
, :
n.parentNode.removeChild(n);

replaceChild() .
.
, . ,
, n :
n.parentNode.replaceChild(document.createTextNode("[ ]"), n);

replace
Child():
// n <b> n .
function embolden(n) {
// ,
// id
if (typeof n == "string") n = document.getElementById(n);
var parent = n.parentNode; // n
var b = document.createElement("b"); // <b>
parent.replaceChild(b, n); // n <b>
b.appendChild(n); // n <b>
}

15.5.1 outerHTML ,
Firefox. 15.5 ,
Firefox ( ,
innerHTML, - Element.pro
totype ).
removeChild() cloneNode().
15.5. outerHTML innerHTML
// outerHTML , .
// , innerHTML,
// Element.prototype .
(function() {
// outerHTML -

416

15.

if (document.createElement("div").outerHTML) return;
// ,
// this
function outerHTMLGetter() {
var container = document.createElement("div"); //
container.appendChild(this.cloneNode(true)); // this
//
return container.innerHTML; //
//
}
// value ,
// this, HTML
function outerHTMLSetter(value) {
//
var container = document.createElement("div");
container.innerHTML = value;
//
while(container.firstChild) // ,
//
this.parentNode.insertBefore(container.firstChild, this);
//
this.parentNode.removeChild(this);
}
// outerHTML
// Element. Object.defineProperty, ,
// __defineGetter__ __defineSetter__.
if (Object.defineProperty) {
Object.defineProperty(Element.prototype, "outerHTML", {
get: outerHTMLGetter,
set: outerHTMLSetter,
enumerable: false, configurable: true
});
}
else {
Element.prototype.__defineGetter__("outerHTML", outerHTMLGetter);
Element.prototype.__defineSetter__("outerHTML", outerHTMLSetter);
}
}());

15.6.4. DocumentFragment
DocumentFragment Node;
. DocumentFragment
:
var frag = document.createDocumentFragment();

Document, DocumentFragment
- . parentNode
null. , Element, DocumentFragment
,
appendChild(), insertBefore() ..

15.6. ,

417

DocumentFragment ,
: Document
Fragment appendChild(), insertBefore() replaceChild(),
, . (
,
.)
DocumentFragment
:
// n
function reverse(n) {
// DocumentFragment,
//
var f = document.createDocumentFragment();
//
// . n
// f, . ,
// f n.
while(n.lastChild) f.appendChild(n.lastChild);
//
// f n.
n.appendChild(f);
}

15.6 insertAdjacentHTML() (15.5.1)


innerHTML DocumentFragment.
HTML ,
insertAdjacentHTML(). fragment()
, , :
DocumentFragment,
HTML.
15.6. insertAdjacentHTML()
innerHTML
// Element.insertAdjacentHTML ,
// , HTML,
// , insertAdjacentHTML:
// Insert.before(), Insert.after(), Insert.atStart(), Insert.atEnd()
var Insert = (function() {
// insertAdjacentHTML,
// HTML, .
if (document.createElement("div").insertAdjacentHTML) {
return {
before: function(e,h) {e.insertAdjacentHTML("beforebegin",h);},
after: function(e,h) {e.insertAdjacentHTML("afterend",h);},
atStart: function(e,h) {e.insertAdjacentHTML("afterbegin",h);},
atEnd: function(e,h) {e.insertAdjacentHTML("beforeend",h);}
};
}
// , insertAdjacentHTML,
//
// insertAdjacentHTML.

418

15.

// ,
// HTML DocumentFragment,
// .
function fragment(html) {
var elt = document.createElement("div"); //
var frag = document.createDocumentFragment(); //
elt.innerHTML = html; //
while(elt.firstChild) //
frag.appendChild(elt.firstChild); // elt frag
return frag; // frag
}
var Insert = {
before: function(elt, html) {
elt.parentNode.insertBefore(fragment(html), elt);
},
after: function(elt, html) {
elt.parentNode.insertBefore(fragment(html),elt.nextSibling);
},
atStart: function(elt, html) {
elt.insertBefore(fragment(html), elt.firstChild);
},
atEnd: function(elt, html) { elt.appendChild(fragment(html)); }
};
// insertAdjacentHTML
Element.prototype.insertAdjacentHTML = function(pos, html) {
switch(pos.toLowerCase()) {
case "beforebegin": return Insert.before(this, html);
case "afterend": return Insert.after(this, html);
case "afterbegin": return Insert.atStart(this, html);
case "beforeend": return Insert.atEnd(this, html);
}
};
return Insert; //
}());

15.7. :
15.7 , .
,
: , ,
, innerHTML
. ,
.
15.7.
/**
* TOC.js: .
*
* ,
* .

15.7. :

419

* id="TOC".
* , , .
*
* <h1> <h6>,
* TOC.
*
* , .
* , "TOC",
* HTML.
*
* CSS.
* "TOCEntry". , ,
* . , <h1>,
* "TOCLevel1", <h2> "TOCLevel2" ..
* , , "TOCSectNum".
*
* , :
*
* #TOC { border: solid black 1px; margin: 10px; padding: 10px; }
* .TOCEntry { font-family: sans-serif; }
* .TOCEntry a { text-decoration: none; }
* .TOCLevel1 { font-size: 16pt; font-weight: bold; }
* .TOCLevel2 { font-size: 12pt; margin-left: .5in; }
* .TOCSectNum:after { content: ": "; }
*
* .
* , :
*
* .TOCSectNum { display: none }
*
* onLoad().
**/
onLoad(function() { // , . .
// .
// , .
var toc = document.getElementById("TOC");
if (!toc) {
toc = document.createElement("div");
toc.id = "TOC";
document.body.insertBefore(toc, document.body.firstChild);
}
//
var headings;
if (document.querySelectorAll) // ?
headings = document.querySelectorAll("h1,h2,h3,h4,h5,h6");
else //
headings = findHeadings(document.body, []);
//
function findHeadings(root, sects) {
for(var c = root.firstChild; c != null; c = c.nextSibling) {
if (c.nodeType !== 1) continue;
if (c.tagName.length == 2 && c.tagName.charAt(0) == "H")
sects.push(c);

420

15.

else
findHeadings(c, sects);
}
return sects;
}
// , .
var sectionNumbers = [0,0,0,0,0,0];
// .
for(var h = 0; h < headings.length; h++) {
var heading = headings[h];
// , .
if (heading.parentNode == toc) continue;
// .
var level = parseInt(heading.tagName.charAt(1));
if (isNaN(level) || level < 1 || level > 6) continue;
//
// .
sectionNumbers[level-1]++;
for(var i = level; i < 6; i++) sectionNumbers[i] = 0;
// ,
// 2.3.1.
var sectionNumber = sectionNumbers.slice(0,level).join(".")
// . <span>,
// CSS.
var span = document.createElement("span");
span.className = "TOCSectNum";
span.innerHTML = sectionNumber;
heading.insertBefore(span, heading.firstChild);
// ,
// .
var anchor = document.createElement("a");
anchor.name = "TOC"+sectionNumber;
heading.parentNode.insertBefore(anchor, heading);
anchor.appendChild(heading);
// .
var link = document.createElement("a");
link.href = "#TOC" + sectionNumber; //
link.innerHTML = heading.innerHTML; //
//
// div,
// .
var entry = document.createElement("div");
entry.className = "TOCEntry TOCLevel" + level;
entry.appendChild(link);
// div .
toc.appendChild(entry);
}
});

15.8.

421

15.8.


.
, ,
. -
,
.
. , 16
,
CSS. CSS
( )
, ,
.
, ,
,
, .
, , (
, IE,
IE IE9).
W3C
CSSOM-View Module (http://www.w3.org/TR/cssom-view/).

15.8.1.
. X ,
Y . ,
: X Y

.
,
: (, ,
). , ,
<iframe>, . ,
, ,
. (
.)
,
,
.
, ,
. , Y
200
75,
Y 125. ,
X 400

422

15.

200,
X 600.
,
, .

.
CSS (16).
(15.8.2). ,
- ,
.
,
. ,
IE 8 , pageXOffset
pageYOffset Window. , IE ( )
scrollLeft scrollTop.
,
(document.documentElement) ,
( 13.4.4) <body>
(document.body) . 15.8 ,
.
15.8.
// x y
function getScrollOffsets(w) {
// ,
//
w = w || window;
// , IE 8
if (w.pageXOffset != null) return {x: w.pageXOffset, y:w.pageYOffset};
// IE ( )
var d = w.document;
if (document.compatMode == "CSS1Compat")
return {x:d.documentElement.scrollLeft,
y:d.documentElement.scrollTop};
//
return { x: d.body.scrollLeft, y: d.body.scrollTop };
}

,
, ,
. ,
IE 8 , ,
IE, , . 15.9
, .

15.8.

15.8.

423

15.9.
// w h
function getViewportSize(w) {
// ,
w = w || window;
// , IE 8
if (w.innerWidth != null) return {w: w.innerWidth, h:w.innerHeight};
// IE ( )
var d = w.document;
if (document.compatMode == "CSS1Compat")
return { w: d.documentElement.clientWidth,
h: d.documentElement.clientHeight };
//
return { w: d.body.clientWidth, h: d.body.clientWidth };
}

scrollLeft, scrollTop, clientWidth


clientHeight. 15.8.5.

15.8.2.

getBoundingClientRect(). IE5
.
left, right, top bottom. left top
X Y , right
bottom .
.
( Client getBoundingClientRect()
-, .. .)
,
,
:
var
var
var
var

box = e.getBoundingClientRect(); //
offsets = getScrollOffsets(); // . ,
x = box.left + offsets.x; //
y = box.top + offsets.y;

, ( W3C) ,
getBoundingClientRect(), width height,
IE .
, :
var box = e.getBoundingClientRect();
var w = box.width || (box.right - box.left);
var h = box.height || (box.bottom - box.top);

16 ,
, (padding).
(border),

424

15.

(margins). , getBoundingClientRect(),
, .
Client getBoundingClientRect()
, Bo
unding ()? , ,
<div>, .
, <span>, <code> <b>,
.
, ( <i>
</i>), . , ,

( , ).
getBoundingClientRect() ,
(bounding rectangle),
. <i>,
, .
,
, getClientRects(),
, , ,
, ,
getBoundingClientRect().
, DOM, getElementsByTagName(),
, .
( ),
getBoundingClientRect() getClientRects()
.
. ,
.

15.8.3.
getBoundingClientRect()
. ,
.
elementFromPoint() Document.
X Y ( , )
Element, .
,
,
( CSS- z-index, 16.2.1.1)
, . ,
, elementFromPoint() null,

.
elementFromPoint() ,
,
. , 17,

15.8.

425

target.
elementFromPoint() .

15.8.4.
15.8 ,
. ,
scrollLeft scrollTop,
,
JavaScript. scrollTo() Window ( scroll())
X Y ( )
.
,
. ,
,
,
.
, :
// . offsetHeight .
var documentHeight = document.documentElement.offsetHeight;
var viewportHeight = window.innerHeight; // getViewportSize(),
//
// , ""
window.scrollTo(0, documentHeight - viewportHeight);

scrollBy() Window scroll() scrollTo(),



. , ,
(13.2.5.1):
// 10 200 .
// , !
JavaScript:void setInterval(function() {scrollBy(0,10)}, 200);

,
, .
getBoundingClientRect(),

scrollTo(), scrollIntoView()
HTML-. , ,
, .
,
.
false, ,
. ,
, ,
.
scrollIntoView() window.location.
hash, ( <a name="">).

426

15.

15.8.5. ,

getBoundingClientRect() ,
,

. :
offsetWidth offsetHeight HTML .
, , .
HTML- offsetLeft offsetTop,
X Y.
.
,
,
-, . offsetParent ,
. offsetParent
null, .
, e
offsetLeft offsetTop :
function getElementPosition(e) {
var x = 0, y = 0;
while(e != null) {
x += e.offsetLeft;
y += e.offsetTop;
e = e.offsetParent;
}
return {x:x, y:y};
}

, offsetParent,
,
. (, getBoundingClientRect(), ,
.)
getEle
mentPosition() , ,
.
offset
;
client, scroll. HTML-
, :
offsetWidth clientWidth scrollWidth
offsetHeight clientHeight scrollHeight
offsetLeft clientLeft scrollLeft
offsetTop clientTop scrollTop
offsetParent

client scroll,
, HTML-
, ,

15.8.

427

( CSS-
overflow 16.2.6).
, ,
,
.
clientWidth clientHeight offsetWidth offsetHeight,
,
. ,
, clientWidth clientHeight
. ,
, <i>, <code> <span>, clientWidth cli
entHeight 0.
clientWidth clientHeight getViewportSize()
15.9. ,
( ),
, innerWidth innerHeight .
clientLeft clientTop :

.
.

( ), clientLeft clientTop
. cli
entLeft clientTop 0.
scrollWidth scrollHeight
, , ,
.
, clientWidth cli
entHeight.
, , ,
clientWidth clientHeight.
, scrollLeft scrollTop
.
getScrollOffsets() (15.8),
. , scrollLeft scrollTop
, .
(HTML- scrollTo(), Window.)
,
, getElementPosition()
- ,
. ,
, ..
:
function getElementPos(elt) {
var x = 0, y = 0;
// ,
for(var e = elt; e != null; e = e.offsetParent) {

428

15.

x += e.offsetLeft;
y += e.offsetTop;
}
// -, .
//
// .
for(var e=elt.parentNode; e != null && e.nodeType == 1; e=e.parentNode) {
x -= e.scrollLeft;
y -= e.scrollTop;
}
return {x:x, y:y};
}

getElementPos()
, getBoundingClientRect() ( ).
, getElementPos(), ,
getBoundingClientRect(). ,
getBoundingClientRect(),
,
. , jQuery,
,
, .
, getBounding
ClientRect(), , , jQuery.

15.9. HTML-
HTML- <form> , <input>, <select>
<button>, .
HTML- ,
JavaScript. HTML -
, JavaScript.
; ;
HTML- (
) .
HTML- -
,
JavaScript-
. , ,
,
. ,
, (
).
, ,
.
,
,
. ,
. ,
, , .

429

15.9. HTML-

,
HTML-. HTML-,
HTML-,
DOM, .
,
JavaScript,
, DOM.
, HTML,
HTML-. ,
HTML- (<input>, <textarea>, <select> .),
. .15.1
.

, Form, Input, Option, Select TextArea.
15.1. HTML-
HTML-

type

<input type="button"> "button"

<button type="button">

onclick

<input type="checkbox"> "checkbox"

onchange

;
,

<input type="file">

"file"

onchange


; value

<input type="hidden">

"hidden"

,
,

<option>

Se
lect;
Select,
Option

<input type="password"> "password"

onchange

<input type="radio">

"radio"

onchange

<input type="reset">

<button type="reset">

"reset"

onclick

<select>

"select-one"

onchange

,

( <opti
on>)

<select multiple>

"select-multiple" onchange

,
(
<option>)

430

15.
15.1 ()

HTML-

type

<input type="submit"> "submit"

<button type="submit">

onclick

<input type="text">

"text"

onchange

;
<input>
type

<textarea>

"textarea"

onchange

15.9.1.
, ,
, getElementById() getElementsByTagName():
var fields = document.getElementById("address").getElementsByTagName("input");

, querySelectorAll(),
, ,
:
// id="shipping"
document.querySelectorAll('#shipping input[type="radio"]');
// name="method" id="shipping"
document.querySelectorAll('#shipping input[type="radio"][name="method"]');

, 14.7, 15.2.2 15.2.3, <form>


name id .
<form> name="address" :
window.address //
document.address //
document.forms.address //
document.forms[n] //

:
name
name id
: n -

15.2.3 , document.forms HTML


Collection, <form> ,
id name. Form
HTMLCollection, ,
. name="address"
name="street",
:
document.forms.address[0]
document.forms.address.street
document.address.street // name="address", id="address"

, ,
elements:

15.9. HTML-

431

document.forms.address.elements[0]
document.forms.address.elements.street


id. name
, .

name . , , HTMLCollection
,
, , ,
.
, :
<form name="shipping">
<fieldset><legend>Shipping Method</legend>
<label><input type="radio" name="method" value="1st"> </label>
<label><input type="radio" name="method" value="2day">
2
</label>
<label><input type="radio" name="method" value="overnite">

</label>
</fieldset>
</form>

:
var methods = document.forms.shipping.elements.method;

, <form> HTML-
method,
elements method.
, ,
checked :
var shipping_method;
for(var i = 0; i < methods.length; i++)
if (methods[i].checked) shipping_method = methods[i].value;

, checked value,
.

15.9.2.
Form elements[],
. Form . acti
on, encoding, method target action,
encoding, method target <form>.
-
. JavaScript
, ,
.
JavaScript
Submit,

432

15.

Reset. JavaScript
, submit() reset(), Form. submit() Form
, reset() .
( ) ,
. , ,
,
.
type
,
. , <input>,
type. ( <text
area> <select>) type,
, ,
<input>.
.15.1.
form
Form,
, null, <form>.
name
, HTML- name.
value
, ,
.
- Ja
vaScript-. Text Textarea
. , <input>
( , <button>),
. value
()
. , HTML- value.
-,
. value
,
.

15.9.3.
Form onsubmit,
, onreset,
. onsubmit
. ,
false. JavaScript-
.
, onsubmit
Submit. submit()
onsubmit.

15.9. HTML-

433

onreset onsubmit.

, false. Reset
, , ,
, :
<form...
onreset="return confirm(' ?')">
...
<button type="reset"> </button>
</form>

onsubmit, onreset
Reset. reset()
onreset.
click change,
, ,
onclick onchange. 15.1
. ,
, , click
(
, ).
change, , .
,
. ,
, ,
. ,
.
. ,
, click
change; change .
focus,
, blur, .
, this
, (
17). form,
, ,
Form, this.form.
, ,
, x, this.form.x.

15.9.4.
, ..
.
, ,
onclick. ,
<input>, , value.

434

15.

, <button>,
.
,
onclick, . , onclick,
, .
.
Submit Reset -,
, ( ).
onclick false,
, , . onclick
Submit ,
onsubmit .
Button. , , <button>,
, Input.

15.9.5.
:
, .
, .
, HTML- name.

.
name, , , ,
, , .
, checked.
, .
defaultChecked
, HTML- checked; ,
, .
-
HTML- ( <label>).
, value
. value ,
, - .
,
onclick.
, onchange.
( ,
, onchange.)

15.9.6.
Text HTML- Java
Script-, , .
. value ,
. , .

15.9. HTML-

435

HTML5 placeholder
, ,
- :
: <input type="text" name="arrival" placeholder="yyyy-mm-dd">

onchange ,
, ,
, .
Textarea ( )
Text , (JavaScript-
) .
<textarea>,
<input>, . (
. Textarea .)
.
value onchange Textarea
, Text.
<input type="password">
,
. , ,
, ,
. , Password
,
(
HTTPS-)
.
, <input type="file">
, -. ,
, ,
. , ,
onchange. , ,
value .
JavaScript- , ,
.
onkey
press, onkeydown onkeyup. false onkey
press onkeydown,
. , ,
. 17.6.

15.9.7. Select Option


Select (
Option), .
Select , , size
1, (,
). Select
, type.

436

15.

<select> multiple,
, type Select selectmultiple. , multiple ,
type select-one.

, .
, Select, -
: <option>. Select
options, , ,
Option.
,
Select onchange. Select
,
selectedIndex .
Select selectedIndex
.

options[] selected Option.
selected Option text,
, Select .
, .
value ,
- .
,
value ( HTML- value)
,
. , Option
; on
change Select.
text Option
Select
options,
. Option,
options.length ,
Option, options.length
. Option Select,
options[] null.
Option, , options[]
, , .
Select ,
Option() options[], :
// Option
var zaire = new Option("Zaire", //
"zaire", //
false, //
false); //

text
value
defaultSelected
selected

// Select, options:

15.10.

437

var countries = document.address.country; // Select


countries.options[countries.options.length] = zaire;

, Select
.
, Document.create
Element(), Node.insertBefore(), Node.removeChild() .

15.10.
,
. .
Document.

15.10.1. Document
Document,
body, documentElement forms,
. ,
:
cookie
, JavaScript-
cookie-. 20.
domain
, -,
, ,
, - (
. 13.6.2.1).
lastModified
, .
location
Location, location
Window.
referrer
URL- , ( ),
.
, HTTP- Referer, r.
title
<title> </title> .
URL
URL , ,
Location.
location.href, , Location,
. ,

438

15.

, location.href ,
document.URL .
referrer:
URL- , ,
. ,
:
if (document.referrer.indexOf("http://www.google.com/search?") == 0) {
var args = document.referrer.substring(ref.indexOf("?")+1).split("&");
for(var i = 0; i < args.length; i++) {
if (args[i].substring(0,2) == "q=") {
document.write("<p> , Google. ");
document.write(" : " +
unescape(args[i].substring(2)).replace('+', ' ');
break;
}
}
}

document.write(), ,
.

15.10.2. document.write()
document.write() , Netscape 2. DOM

. ,
.
document.write()
, .

. , write()
HTML-:
<script>
document.write("<p> : " + document.title);
document.write("<br>URL: " + document.URL);
document.write("<br> : " + document.referrer);
document.write("<br>: " + document.lastModified);
document.write("<br>: " + new Date());
</script>

, write()
HTML .
document.write() <script>
,
. document.write()
,

! ( , .)

15.10.

439

document.write()
defer async.
13.3 13 document.write() ,
.
write()
. (
,
.) write()
. write()
, . ,
write(), ( ),
close() ,
,
.
, Document writeln(),
write(), ,
. ,
, <pre>.
document.write() :
innerHTML , DOM,
. ,
/,
write(). ,
, , ,
15.10, innerHTML
write() close().
15.10. - innerHTML
// " /" innerHTML .
function ElementStream(elt) {
if (typeof elt === "string") elt = document.getElementById(elt);
this.elt = elt;
this.buffer = "";
}
//
ElementStream.prototype.write = function() {
this.buffer += Array.prototype.join.call(arguments, "");
};
// , write(),
ElementStream.prototype.writeln = function() {
this.buffer += Array.prototype.join.call(arguments, "") + "\n";
};
// .
ElementStream.prototype.close = function() {
this.elt.innerHTML = this.buffer;
this.buffer = "";
};

440

15.

15.10.3.
,
. , :
function getSelectedText() {
if (window.getSelection) // , HTML5
return window.getSelection().toString();
else if (document.selection) // , IE.
return document.selection.createRange().text;
}

window.getSelection() Selection,
,
Range. Selection Range
,
. (, IE)
Selection toString(),
.
IE ,
. document.selection ,
. createRange()
IE TextRange, text .
, , ,
(13.2.5.1)
. , HTML-
.
URL- javascript:,
:
<a href="javascript: var q;
if (window.getSelection) q = window.getSelection().toString();
else if (document.selection) q = document.selection.createRange().text;
void window.open('http://ru.wikipedia.org/wiki/' + q);">

</a>

, , ,
. getSelection() Window
, <input> <textarea>:
, .
document.selection, IE, ,
.
, <text
area>, :
elt.value.substring(elt.selectionStart, elt.selectionEnd);

selectionStart selectionEnd IE8 .

441

15.10.

15.10.4.
,
textarea,
. IE -
HTML.
(, ,
),
, (
, ), .
.
HTML- contenteditable Ja
vaScript- contenteditable Element,
.
,
. HTML-,
:
<div id="editor" contenteditable>
,
</div>


contenteditable. ,
, .
, spellcheck.
spellcheck=false (, , <textarea>
,
).
,
designMode Document on. (
, off.)
designMode HTML-.
, <iframe>,
( , onLoad()
13.5):
<iframe id="editor" src="about:blank"></iframe> //
<script>
onLoad(function() { //
var editor = document.getElementById("editor"); //
editor.contentDocument.designMode = "on"; //
}); //
</script>

contenteditable designMode.
,
.
.
Enter ,

442

15.

. ,
<br/>.
,
Ctrl-B, .
( Firefox)
, Ctrl-B Ctrl-I, ,
, .
,
.
, execCommand() Document.
( , Document,
contenteditable. ,
,
.) , execCommand(),
, bold, subscript, justifycenter insertimage.
execCommand() .
. , createlink
URL . ,
execCommand() true,
.
, false
.
,
execCommand():
function bold() { document.execCommand("bold", false, null); }
function link() {
var url = prompt(" ");
if (url) document.execCommand("createlink", false, url);
}

, execCommand(),
.
, .
, ,
document.queryCommandSupported(). document.queryCom
mandEnabled() , . (,
, ,
, .) ,
bold italic,

. ,
-.
document.queryCommandState().
, , fontname,
( ).
document.queryCommandValue().
, fontname

15.10.

443

.
document.queryCommandIndeterm().
.
, bold, italic, createlink, undo redo,
.1
HTML5 , . ,
, -
:
bold insertLineBreak selectAll
createLink insertOrderedList subscript
delete insertUnorderedList superscript
formatBlock insertParagraph undo
forwardDelete insertText unlink
insertImage italic unselect
insertHTML redo

-
, , ,
, .
.2
, , ,
,
,
. , ,
HTML, , .

contenteditable, innerHTML,
HTML .
, .
.

, 18.
, , 20.

http://www.quirksmode.org/
dom/execCommand.html.

YUI Dojo .
http://en.wikipedia.org/wiki/Online_rich-text_editor.

16
16.

(Cascading Style Sheets, CSS)


HTML-.
: ,
, , ,
. ,
JavaScript,
,
- , , ,

. ,
. CSS Java
Script, ,
HTML (Dynamic HTML,
DHTML), .
CSS ,
. CSS ,
,
.1
,
CSS .
CSS, ,
.
CSS. 16.3
: ,
HTML- style. style
,
. 16.4 ,

: CSS .
, 3- . . .: -, 2008.

16.1. CSS

445

. 16.5 ,
style .
,
. 16.6 ,
,
.

16.1. CSS
HTML-
: , , ..
CSS, (style properties).
CSS , , , ,
, , ,
. HTML-,
CSS-.
:
font-weight: bold

,
.
/, :
margin-left: 10%; /* 10% */
text-indent: .5in; /* 1/2 */
font-size: 12pt; /* 12 */

, ,
/* */. ,
//.
CSS- HTML-
, .
style HTML-.
:
<p style="margin: 20px; border: solid red 2px;">
.
</p>

CSS HTML-
.
HTML-,
. , , ,
id class,
. 15.2.5,
, querySelectorAll() ,
.
CSS ,
,
. :

446

16.

p { /* "p" <p> */
text-indent: .5in; /* 0,5 */
}
.warning { /* class="warning" */
background-color: yellow; /* */
border: solid black 5px; /* */
}

CSS HTML-, <sty


le> </style> <head>. <script>,
<style>
HTML:
<html>
<head><title> </title>
<style>
body { margin-left: 30px; margin-right: 15px; background-color: #ffffff }
p { font-size: 24px; }
</style>
</head>
<body><p>, </p>
</html>

-,
, HTML. CSS HTML-.
<script>, <style> src.
HTML-, <link>
<head> :
<head>
<title> </title>
<link rel="stylesheet" href="mystyles.css" type="text/css">
</head>

, .
CSS ,
.

16.1.1.
, C CSS cascade ().
, ,
, :
-

style HTML-
, style, ,
,
.
. ,
.

16.1. CSS

447

,
. (
, ,
, ,
, .)
-
style
.
, .
.

16.1.2. CSS
CSS . 1996
CSS1 , , ,
. , Netscape 4 Internet Explorer 4,
CSS1. , CSS2,
1998; ,

. CSS2.1 CSS2.
, .
CSS2.1,
IE, IE8, .
CSS . CSS
,
. CSS
http://www.w3.org/Style/CSS/current-work.

16.1.3.
, ,
, . , font-family,
font-size, font-style font-weight
font :
font: bold italic 24pt helvetica;

border, margin padding


, , (
) .
, ,
border border-left, border-right, bor
der-top border-bottom.
. border-top border-top-co
lor, border-top-style border-top-width.

16.1.4.
CSS,
. Firefox

448

16.

moz-, Chrome -webkit-, IE -ms-.


, , , ,
. borderradius, .
Firefox3 Safari4,
. ,
Firefox 4 Safari 5 ,
border-radius . (Chrome Opera
. IE9 , IE8
, .)
CSS,
, :
.radius10 {
border-radius: 10px; /* */
-moz-border-radius: 10px; /* Firefox3.x */
-webkit-border-radius: 10px; /* Safari3.2 4 */
}

, radius10
class , .

16.1.5. CSS-
16.1 HTML-,
. , ,
class id, ,
style. .16.1 , .

.16.1. -, CSS

16.1. CSS
16.1.
<head>
<style type="text/css">
/* , . */
h1, h2 { color: blue; font-style: italic }
/*
* class="WARNING"
* , .
*/
.WARNING {
font-weight: bold;
font-size: 150%;
margin: 0 1in 0 1in; /* , */
background-color: yellow;
border: solid red 8px;
padding: 10px; /* 10 4 */
}
/*
* h1 h2 class="WARNING"
* , .
*/
.WARNING h1, .WARNING h2 { text-align: center }
/*
* id="special"
* .
*/
#special {
text-align: center;
text-transform: uppercase;
}
</style>
</head>
<body>
<h1> </h1>
<div class="WARNING">
<h2></h2>
!
,
. ,
.
</div>
<p id="special">
<br>
.<br>
<span style="text-transform: none">
.
</span>
</p>

449

450

16.

CSS
, CSS
:
, border-radius, text-shadow, box-shadow columncount. CSS -:
CSS- @font-face
. ( ,
-,
Google http://code.google.com/web
fonts.)

CSS Transitions.
,
CSS . (
,
, ,
CSS, 16.3.1.)
CSS Transitions , IE,
.
CSS Animations, CSS
Transitions ,
. CSS Animations
-, Webkit.
, , -,
.
, CSS, -
, CSS Transforms,
(, , ,
, ),
. ( IE9 )
,
. , Safari ,
, ,
.

16.2. CSS-
JavaScript
CSS-, ,
. CSS-
, ,
, , , . CSS-
, . .16.1
.

16.2. CSS-

451

16.1. CSS-

position

top, left

bottom, right

width, height

z-index


( )

display

visibility

clip

(
, )

overflow

, , ,

margin, border, padding


background

opacity

( ) .
CSS3
. IE

16.2.1. CSS
CSS- position , .
:
static
, . ,

(
).
top, left .
CSS
position .
absolute

.

.
, ,
, .
fixed

.
. ,

452

16.


.
,
IE6.
relative
position relative,
,
. ,
,
, , ,

.
position , static,
left, top, right
bottom. left top,
- (
)
. ,
100 100 ,
CSS- style, :
<div style="position: absolute; left: 100px; top: 100px;">

, top left
,
position , static.
, top left

.
, ,
position:relative 0px top
left .
.

.

left top,

- right bottom. ,
,
(,
):
position: absolute; right: 0px; bottom: 0px;

10 ,
10
, :
position: fixed; right: 10px; top: 10px;

16.2. CSS-

453

CSS .
width height. ,
HTML
. width, height background-color ,
:
<div style="position: absolute; top: 10px; left: 10px;
width: 10px; height: 10px; background-color: blue">
</div>


, left right. ,
, top bottom.
left, right width, width right,
,
height.
,
. , ,
. , ,
,

.
CSS , ,
, .
px,
pixels (). :
(in), (cm), (pt) em (
).
, , CSS
-.
, HTML ,
- ( )
:
<div style="position: absolute; left: 25%; top: 25%; width: 50%; height: 50%;
border: 2px solid black">
</div>

16.2.1.1. : z-index
, left, top, right bottom
X Y -. z-index
- :
,
. z-index
. ,
.
, z-index , ..
z-index .
z-index,

454

16.

,
.
, z-index
(.. ).
,
z-index , .
z-index
.
(
position:static)
, z-index .
z-index, , ..
z-index
,
z-index .

16.2.1.2. CSS:

CSS3 text-shadow,
.
,
CSS- ,
, , :
<!-- text-shadow -->
<span style="text-shadow: 3px 3px 1px #888"></span>
<!- , .
-->
<span style="position:relative;">
<!-- , . -->
<span style="position:absolute; top:3px; left:3px; z-index:-1; color: #888">
<!-- -->
</span>
</span>

, ,
<span>. , ,
.
<span>,
<span> ( ). z-index
.

16.2.2. ,
CSS , .
, (
) . CSS- ,
:

16.2. CSS-
border: solid black 1px; /*
/*
border: 3px dotted red; /*
/*

455

,
1 */
*/
3 */

, CSS-,
. ,
, border-bottom.
,
, border-top-width border-left-color.
CSS3 , border-radius,
, . :
border-top-right-radius: 50px;

margin padding .
( ) , margin
,
, padding , .
(margin) (,
) .
(padding) .
, .
,
, .
margin padding:
margin: 5px; padding: 5px;


:
margin-left: 25px;
padding-bottom: 5px;


margin padding,
: , , . ,

:
padding: 1px 2px 3px 4px;
/* . */
padding-top: 1px;
padding-right: 2px;
padding-bottom: 3px;
padding-left: 4px;

margin .

16.2.3. CSS
margin, border padding, ,
, . ,

456

16.

, , ,
CSS, ,
, CSS- .
.16.2 CSS ,
top, left, width height .
bordertopwidth

top

left

paddingtop

borderrightwidth

paddingleft

height
paddingright

width
borderleftwidth

paddingbottom
borderbottomwidth

.16.2. CSS: ,

.16.2 ,
-. , ,
, CSS-,
-.
, margin:
.
.16.2 . -, width
height
, ( )
. ,
,
,
.
-, left top
.
,
, .
right bottom
, .
. ,
,

16.2. CSS-

457

10, 5.
,
. left
0px, ,
.
, ,
(.. ).
,
left top 10px.

16.2.3.1. border-box box-sizing


CSS , width height

. content-box.
, IE CSS.
IE 6 IE6, 7 8
( <!DOCTYPE>
), width height
.
IE , , IE,
. , CSS3
box-sizing. content-box,
, , .
box-sizing: border-box,
IE width height .
border-box ,
, :
<div style="box-sizing:border-box; width: 50%;
padding: 10px; border: solid black 2px;">

box-sizing ,
. Chrome Safari -webkitbox-sizing. Firefox -moz-box-sizing. Opera IE8 ()
box-sizing .
border-box, CSS3,
:
<div style="width: calc(50%-12px); padding: 10px; border: solid black 2px;">

CSS- calc()
IE9 Firefox4 ( -moz-calc()).

16.2.4.
CSS-: visibi
lity display. visibility :
hidden, , visible, .
display
, , , ,

458

16.

- . display none,
.
visibility display
.
, ,
visibility hidden ,
.
. display
none, ;
, .
display , ,
.
, visibility
display, ,
JavaScript, -
! , .

16.2.5. ,
, ,
CSS- color. backgroundcolor. ,
border-color border.
,
, red
() black (). CSS
,
,
, , .
. :
#000000 /*
#fff /*
#f00 /*
#404080 /*
#ccc /*

*/
*/
- */
- */
- */

CSS3
RGBA ( , -
, ). RGBA
, IE; , ,
IE9. CSS3 HSL (hue-satu
ration-value --) HSLA.
Firefox, Safari Chrome, IE.
CSS , ,
,
( )
.
CSS,

16.2. CSS-

459

<canvas>. (
21.)
background-color ,
.
background-image , background-attach
ment, background-position background-repeat
. background,
. ,
,
, .
,
, . ,
<div>
, <div>.
<div> ,
, .
. ,
, , <button>,
.
background-color;
(transparent).
, , ,
: , .
(
, ). (
. 16.3.) opacity,
CSS3. 0 1, 1
100- ( ), 0 100-
. opacity
, IE. IE
filter. 75%,
CSS-:
opacity: .75; /* CSS3 */
filter: alpha(opacity=75); /* IE; */
/* */

16.2.6. : overflow clip


visibility .
overflow clip . overflow
, , ,
(, width height).
:
visible

. .

460

16.

hidden
, , ,
,
.
scroll

. ,
. ,
;
, , , , , .
auto
,
.
overflow , ,
, clip
, ,
.
, .
clip . CSS2
, clip
,
. clip:
rect(top right bottom left)

top, right, bottom left


. , ,
100100,
style:
style="clip: rect(0px 100px 100px 0px);"

,
, px
. .
, ,
. auto
,
. , 100
style:
style="clip: rect(auto 100px auto auto);"

, ,
, .

16.2.7. :
,
CSS-. 16.2 CSS-

461

16.2. CSS-


, . .16.3.

.16.3. , CSS

JavaScript- ,
(
), ,
CSS.
16.2. CSS-
<!DOCTYPE html">
<head>
<style type="text/css">
/**
* CSS- ,
* "".
*
* .
* .
**/
div.window { /* */
position: absolute; /* */
width: 300px; height: 200px; /* */
border: 3px outset gray; /* 3D- */
}
div.titlebar { /*
position: absolute; /*
top: 0px; height: 18px; /*
width: 290px; /*
background-color: #aaa; /*

, */
*/
18px + */
290 + 5px = 300 */
*/

462
border-bottom: groove gray 2px; /*
padding: 3px 5px 2px 5px; /*
/*
font: bold 11pt sans-serif; /*
}

16.
*/
:
, , , */
*/

div.content { /* , */
position: absolute; /* */
top: 25px; /* 18px +2px +3px+2px */
height: 165px; /* 200px - 25px - 10px */
width: 290px; /* 300px - 10px */
padding: 5px; /* */
overflow: auto; /* */
background-color: #ffffff; /* */
}
div.translucent { /* */
opacity: .75; /* */
filter: alpha(opacity=75); /* IE */
}
</style>
</head>
<body>
<!-- : div "" div -->
<!-- , . , -->
<!-- style, -->
<!-- -->
<div class="window" style="left: 10px; top: 10px; z-index: 10;">
<div class="titlebar"> </div>
<div class="content">
1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>0<br><!-- -->
1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>0<br><!-- . -->
</div>
</div>
<!-- , -->
<div class="window" style="left: 75px; top: 110px; z-index: 20;">
<div class="titlebar"> </div>
<div class="content translucent"
style="background-color:#ccc; font-weight:bold;">
. <tt>z-index</tt>
. CSS-
, .
</div>
</div>
</body>

,
.
,
,
. HTML-,
, ,
. .

16.3.

463

16.3.
CSS
style . HTML-
, style Element,
JavaScript. style
: ,
CSSStyleDeclaration. CSS-,
HTML- style. ,
e , ,
,
font-size, font-weight color:
e.style.fontSize = "24pt";
e.style.fontWeight = "bold";
e.style.color = "blue";

CSSStyleDeclaration ,
. style
:
position: absolute; font-family: sans-serif; background-color: #ffffff;

e JavaScript,
:
e.style.position = "absolute";
e.style.fontFamily = "sans-serif";
e.style.backgroundColor = "#ffffff";

, .
, JavaScript. ,
CSS, ,
JavaScript.
, ,
. left
:
e.style.left = 300; // : ,
e.style.left = "300"; // :

JavaScript
, .
left e, 300
:
e.style.left = "300px";

left ,
:
e.style.left = (x0 + left_margin + left_border + left_padding) + "px";

,
.

464

16.

: CSS- JavaScript
CSS- , font-size,
. JavaScript ,
, :
e.style.font-size = "24pt"; // !

, CSSStyleDeclaration
CSS-. CSS-
, CSSStyleDeclaration
,
. , CSS- border-left-width
borderLeftWidth, CSS- font-family
:
e.style.fontFamily = "sans-serif";

, CSS-, float, ,
JavaScript,
css, CSSStyle
Declaration. , CSS-
float , cssFloat CSSStyleDec
laration.

, CSS-, margin,
, margin-top, margin-right,
margin-bottom margin-left. CSSStyleDeclaration ,
. , margin
:
e.style.margin = topMargin + "px " + rightMargin + "px " +
bottomMargin + "px " + leftMargin + "px";

, , -
:
e.style.marginTop = topMargin + "px";
e.style.marginRight = rightMargin + "px";
e.style.marginBottom = bottomMargin + "px";
e.style.marginLeft = leftMargin + "px";

style HTML- ,
CSS.
,
. CSSStyleDeclaration,
, ,
JavaScript
HTML- style, .
, ,

16.3.

465

30, leftMargin
, ,
style, ,
.
,
, ,
:
CSS-,
. ,
.
,
, 16.4.

, CSSStyleDeclaration.
getAttribute() setAttribute() Element
cssText CSSStyleDeclaration:
// , , style
// e s:
e.setAttribute("style", s);
e.style.cssText = s;
// , , style
// e :
s = e.getAttribute("style");
s = e.style.cssText;

16.3.1.
CSS
CSS
.
setTimeout() setInterval() ( 14.1),
, .
16.3 , shake() fadeOut(). shake()
, (shakes), .
, ,
. fadeOut()
( 500),
.
16.3. CSS
// e .
// id
// . , e
// .
// e. 5 .
// , .
// 500 .
function shake(e, oncomplete, distance, time) {

466
//
if
if
if

16.

(typeof e === "string") e = document.getElementById(e);
(!time) time = 500;
(!distance) distance = 5;

var originalStyle = e.style.cssText; //


e.style.position = "relative"; //
var start = (new Date()).getTime(); //
animate(); //

e
.

// e.
// ,
// e. e .
function animate() {
var now = (new Date()).getTime(); //
var elapsed = now-start; // ?
var fraction = elapsed/time; // ?
if (fraction < 1) { //
// x e
// . ,
// 4pi,
// .
var x = distance * Math.sin(fraction*4*Math.PI);
e.style.left = x + "px";
// 25
// .
// , 40 /.
setTimeout(animate, Math.min(25, time-elapsed));
}
else { //
e.style.cssText = originalStyle // .
if (oncomplete) oncomplete(e); // -
}
}
}
// e
// . , ,
// , e . oncomplete - ,
// e .
// time , 500 .
// IE, ,
// opacity
// filter, IE.
function fadeOut(e, oncomplete, time) {
if (typeof e === "string") e = document.getElementById(e);
if (!time) time = 500;
// " ",
// , Math.sqrt: ,
// .
var ease = Math.sqrt;
var start = (new Date()).getTime(); //

16.3.

467

animate(); //
function animate() {
var elapsed = (new Date()).getTime()-start; //
var fraction = elapsed/time; //
if (fraction < 1) { //
var opacity = 1 - ease(fraction); // .
e.style.opacity = String(opacity); // e
setTimeout(animate, //
Math.min(25, time-elapsed)); //
}
else { //
e.style.opacity = "0"; // e
if (oncomplete) oncomplete(e); // -
}
}
}

, shake() fadeOut(),
. ,
. ,
,
. HTML ,
, :
<button onclick="shake(this, fadeOut);"> </button>

, shake() fadeOut() .

CSS-. ,
jQuery, ,

, shake(),
- .

Scriptaculous,
Prototype.
http://script.aculo.us/ http://scripty2.com/.
CSS3 Transitions
,
. , fadeOut()
CSS, :
.fadeable { transition: opacity .5s ease-in }

, ,
fadeable, (
)
. CSS Transitions ,
Safari Chrome -webkittransition. Firefox 4
-moz-transition.

468

16.

16.4.
style .

CSS- .
,
. , ,
.
, ( )
, :
, .
, CSSStyleDeclaration.
,
. , CSSStyleDeclaration
,
.
getComputed
Style() Window. ,
.
, null ,
CSS,
:before, :after, :first-line :first-letter:
var title = document.getElementById("section1title");
var titlestyles = window.getComputedStyle(element, null);

getComputedStyle() CSSStyleDec
laration, , (
). CSSStyleDeclaration,
,
:
.
:
, ,
. , (,
) , .
px,
,
. ,
, rgb(#,#,#) rgba(#,#,#,#).
, ,
, . ,
margin,
marginLeft, marginTop ..
cssText .
. 16.4
scale() scaleColor().
;

16.4.

469

.
,
. ( IE8 :
, IE getComputedStyle().)
16.4.
// e factor
function scale(e, factor) {
// ,
var size = parseInt(window.getComputedStyle(e,"").fontSize);
// ,
e.style.fontSize = factor*size + "px";
}
// e, .
// factor > 1 , factor < 1 .
function scaleColor(e, factor) {
var color = window.getComputedStyle(e, "").backgroundColor; //
var components = color.match(/[\d\.]+/g); // r,g,b a
for(var i = 0; i < 3; i++) { // r, g b
var x = Number(components[i]) * factor;//
x = Math.round(Math.min(Math.max(x, 0), 255)); //
components[i] = String(x);
}
if (components.length == 3) // rgb()
e.style.backgroundColor = "rgb(" + components.join() + ")";
else // rgba()
e.style.backgroundColor = "rgba(" + components.join() + ")";
}

,
.
font-family:
. fontFamily
font-family,
. ,
arial,helvetica,sans-serif,
. ,
,
top left auto.
CSS , , .
getComputedStyle() IE8 , ,
, IE9. IE HTML-
currentStyle, CSSStyleDeclaration.
currentStyle IE ,
- ,
. IE
, %
em, , red.
CSS ,
,

470

16.

. ,
15.8.2.

16.5. CSS-
CSS- style
HTML- class.
, ,
CSS-. ,
,
( ) .
attention:
.attention { /* , */
background-color: yellow; /* */
font-weight: bold; /* */
border: solid black 2px; /* */
}

class JavaScript ,
HTML- class JavaScript-
className. ,
className , attention:
function grabAttention(e) { e.className = "attention"; }
function releaseAttention(e) { e.className = ""; }

HTML- CSS- class


, .
className :
classNames. , className
, ,
.
, grabAttention()
, className.
HTML5 , classList
. DOMTokenList:
(7.11), ,
, .
, add() remove(),
class . toggle()
, , . ,
contains() class.
DOM, DOMTokenList
,
, classList.
DOMTokenList, classList
, className ,
DOMTokenList.
, DOMTokenList,
className.

16.5. CSS-

471

classList
.
, 16.5. ,
class ,
, CSS.
16.5. classList(): className, CSS-
/*
* classList e, .
* , DOMTokenList.
* contains(), add(), remove(), toggle() toString(),
* e. classList
* , , ,
* length .
* DOMTokenList , toArray(),
* .
*/
function classList(e) {
if (e.classList) return e.classList; // e.classList,
else return new CSSClassList(e); //
}
// CSSClassList - JavaScript, DOMTokenList
function CSSClassList(e) { this.e = e; }
// true, e.className c, - false
CSSClassList.prototype.contains = function(c) {
// , c
if (c.length === 0 || c.indexOf(" ") != -1)
throw new Error(" : '" + c + "'");
//
var classes = this.e.className;
if (!classes) return false; // e
if (classes === c) return true; // e ,
//
// RegExp c
// \b - .
return classes.search("\\b" + c + "\\b") != -1;
};
// c e.className,
CSSClassList.prototype.add = function(c) {
if (this.contains(c)) return; // ,
var classes = this.e.className;
if (classes && classes[classes.length-1] != " ")
c = " " + c; // ,
this.e.className += c; // c className
};
// c e.className
CSSClassList.prototype.remove = function(c) {
// , c -
if (c.length === 0 || c.indexOf(" ") != -1)
throw new Error(" : '" + c + "'");

472

16.

// c
var pattern = new RegExp("\\b" + c + "\\b\\s*", "g");
this.e.className = this.e.className.replace(pattern, "");
};
// c e.className, , true.
// c e.className false.
CSSClassList.prototype.toggle = function(c) {
if (this.contains(c)) { // e.className c
this.remove(c); // .
return false;
}
else { // :
this.add(c); // .
return true;
}
};
// e.className
CSSClassList.prototype.toString = function() { return this.e.className; };
// e.className
CSSClassList.prototype.toArray = function() {
return this.e.className.match(/\b\w+\b/g) || [];
};

16.6.
, CSS-
.
CSS. ,
,
.

. Element, <style>
<link>, .
, id,
document.getElementById(). CSS
StyleSheet, . document.styleSheets
, ,
CSSStyleSheet, .
<style> <link>,
, title,
CSSStyleSheet , title.
,
<style> <link> .

16.6.1.

. <style> <link> CSSStyleSheet

16.6.

473

disabled, JavaScript
. , disabled true,
.
disableStylesheet(), .
,
document.styleSheets. ,
CSS, document.querySelectorAll() (15.2.5)
true disabled :
function disableStylesheet(ss) {
if (typeof ss === "number")
document.styleSheets[ss].disabled = true;
else {
var sheets = document.querySelectorAll(ss);
for(var i = 0; i < sheets.length; i++)
sheets[i].disabled = true;
}
}

16.6.2. ,


CSSStyleSheet API ,
. IE8
API, , .
,
. ,
className
. ,
-,
.
CSSStyleSheet document.styleSheets[]. CSSStyle
Sheet cssRules[], :
var firstRule = document.styleSheets[0].cssRules[0];

IE rules, cssRules.
cssRules[] rules[] CSSRule.
API CSSRule CSS- ,
@-, @import @page. IE rules[]
.
CSSRule ,
. ( API , ,
, , ,
.) selectorText CSS-
, style CSSStyleDec
laration, , . ,
CSSStyleDeclaration ,

474

16.

. CSSStyleDeclaration
.
,
.
cssText CSSStyleDeclaration,
.


. insert
Rule() deleteRule(), :
document.styleSheets[0].insertRule("H1 { text-weight: bold; }", 0);

IE insertRule() deleteRule(),
addRule() removeRule().
( ) , addRule()
.

API, :
var ss = document.styleSheets[0]; //
var rules = ss.cssRules?ss.cssRules:ss.rules; //
for(var i = 0; i < rules.length; i++) { //
var rule = rules[i];
if (!rule.selectorText) continue; // @import .
var selector = rule.selectorText; //
var ruleText = rule.style.cssText; //
// h1, h2
// , ,
// "h1"
if (selector == "h1") {
if (ss.insertRule) ss.insertRule("h2 {" +ruleText+ "}", rules.length);
else if (ss.addRule) ss.addRule("h2", ruleText, rules.length);
}
// text-decoration, .
if (rule.style.textDecoration) {
if (ss.deleteRule) ss.deleteRule(i);
else if (ss.removeRule) ss.removeRule(i);
i--; // ,
// i+1 i
}
}

16.6.3.
,
.
, DOM:
<style> <head>,
innerHTML . IE8

16.6.

475

CSSStyleSheet
document.createStyleSheet(),
cssText. 16.6 .
16.6.
// .
// styles . ,
// . ,
// , .
// , -
function addStyles(styles) {
//
var styleElt, styleSheet;
if (document.createStyleSheet) { // IE API,
styleSheet = document.createStyleSheet();
}
else {
var head = document.getElementsByTagName("head")[0]
styleElt = document.createElement("style"); // <style>
head.appendChild(styleElt); // <head>
//
styleSheet = document.styleSheets[document.styleSheets.length-1]
}
//
if (typeof styles === "string") {
//
if (styleElt) styleElt.innerHTML = styles;
else styleSheet.cssText = styles; // IE API
}
else {
// -
var i = 0;
for(selector in styles) {
if (styleSheet.insertRule) {
var rule = selector + " {" + styles[selector] + "}";
styleSheet.insertRule(rule, i++);
}
else {
styleSheet.addRule(selector, styles[selector], i++);
}
}
}
}

17
17.

JavaScript
, (
13.3.2). -
, - .
, - ,
,
. JavaScript-
,
,
. , -
:
, -
(.. ), .
, ,
. ,
.
JavaScript .
, ,
,
. .
, . mousemove,
, , . key
down , . load ,
( - ) .
, .
,
, . -
, 17.1.
,
. , .

477

: load Window click <button>.


Java
Script Window, Document Element,
. , 18
readystatechange, XMLHttp
Request.
, , ,
, .1
-, .
,
. -
, , ,
. ,
17.2 17.3.
,
.
( IE8 ,
event).
type, , target,
. (IE8 target
srcElement.)
. , ,
, , ,
,
-.
, type target,
.
, .
, Event.
.

Event .2
, ,
. ,
( load Window),
. ,
, , ,
1

, HTML5,
, ,
. .


. Event ,
. , MouseEvent
, ,
, KeyEvent ,
.
Event.

478

17.

. ,
mousemove <a>,
. : , <p>,
<div> Document.
Document
,
. ,

.
. 17.3.6.
,
,
,
. IE8
.

; , 17.2.

. , click, ,
.
,
,
. ;
17.3.7.
, ,
. , ,
, -.
- ,
,
-.
, .
,

. - JavaScript -
IE8
, .
, ,
. :





17.1.

479

17.1.
-
: load, click, mouseover
.
17.1.1. -
,
. ,
,
.
:
DOM Level3 Events,
W3C. DOM
17.1.2.
HTML5 (
) ,
, , ,
drag-and-drop ( ),
- .
17.1.3.
,
JavaScript, iPhone,
. ,
, Apple, 17.1.4.
,
,
.
, .

. ,
, ,

.

17.1.1.
, -
,
: , ,
HTML- Window.
.

17.1.1.1.
-,

JavaScript. ,
. <form>

480

17.

submit, , reset,
. , (
), click,
. ,
, change,
, , .
change ,

. ,
focus blur .
, , 15.9.3.
.


,
,
:
-

, .
, mousedown, mousemove, mouse
up, keydown, keypress keyup, ,
, touchmove gestu
rechange.
-
-
. , click ,
( ).
,
(
) . textinput (
) -
keypress
, ,
.

,
HTML-,
-. focus (
, ), change (
, ,
) submit (,
).

17.1.

481



,

. load, Window
, , ,
.
DOMContentLoaded (
13.3.4). ,
HTML5 ( 22.2), popstate
Back () .
-, HTML5
(20.4), online offline. 18
, readystatechange,
. API
, ( 22.6.5),
, loadstart, progress loadend,
-.

, HTML5
,
. drag-and-drop (17.7) ,
dragstart, dragenter, dragover drop. ,
,
. <video> <audio>
( 21.2), HTML5,
, waiting, playing,
seeking, volumechange ..
-,
- .

( 14)

JavaScript .

,
, , , 14.1
14.6 , , .

submit reset ,
,
click. , focus
blur. IE focusin focusout,
focus blur. jQuery (19)
focusin focusout , .

482

17.

, DOM Level 3
Events.
, , , IE, input
<textarea> ,
( ) .
change, input
. , , input,
, . (
textinput, .)

17.1.1.2. Window
Window ,
, ,
. ( ,
, .)
load:
,
( ). load
13. load DOMContentLoaded
readystatechange: ,
, ,
. ,
, 17.4.
unload load:
, . unload
, ,
. beforeunload
unload, ,
-. beforeunload
, ,
;
.
onerror Window ,
Ja
vaScript. ,
. 14.6.
load error
, <img>. ,
(, )
, .
abort ( HTML5),
, ( ,
) - , .
focus blur,
, Window: ,
.

17.1.

483

, resize scroll Window,


. scroll
, ,
CSS- overflow (16.2.6). ,
resize scroll, Event,
,
. ,
, 15.8.

17.1.1.3.
,
.
, ,
. ,
, , ,
, -
. clientX clientY
. button which ,
. (
Event , ,
.) altKey, ctrlKey, metaKey shiftKey
true,
-. detail
click , , .
mousemove ,
. ,
. mousedown mouseup
, .
mousedown,
mousemove,
.
, mousemove,
,
. 17.5 .
mousedown mouseup
click. click , -
,
, ,
,
. (
), dblclick.
,
. , ,
contextmenu, , ,
. ,
.
,
, mouseover .

484

17.

,
mouseout. rela
tedTarget, , . (
relatedTarget IE Event.)
mouseover mouseout ,
. ,
mouseout ,

. IE
, mouseenter mouseleave. jQuery
, IE (19), ,
DOM Level3 Events.
, mou
sewheel ( Firefox DOMMouseScroll). ,
, , ,
. DOM
Level3 Events
, , , , mousewheel DOM
MouseScroll. mousewheel 17.6.

17.1.1.4.
- ,
, .
,
,
JavaScript.
, ,
. ,
.
, keyCode,
, .
keyCode altKey,
ctrlKey, metaKey shiftKey, -.
keydown keyup
: ,
( -). keydown
, , key
down, keyup key
press. (
, , keyup
keypress.) keypress

, .
keydown, keyup keypress ,
- ,
keyCode .
DOM Level 3 Events, ,
, .

17.1.

485

keydown 17.9, 17.8


keypress.

17.1.2. DOM
DOM Level3 Events W3C
.

.
, ,
, .
,
.
, DOM Level3 Events
focusin focusout focus
blur, mouseenter mouseleave
mouseover mouseout. ,
,
DOM Level2 Events, .
- , DOMActivate,
DOMFocusIn DOMNodeInserted, ,
.1
, DOM Level 3 Events,

wheel text
input KeyboardEvent,
keydown, keyup keypress.
wheel
, ,
, deltaX, deltaY deltaZ,
. (
, deltaZ
.) mousewheel
17.6.
DOM Level3 Events keypress, ,

textinput.
keyCode, , textinput,
data, . textinput
:
,
, , (drag-and-drop)
.. inputMethod
, (,
1

,
DOM, DOMContentLoaded.
Mozilla DOM Events.

486

17.

,
..).
Safari Chrome textInput.
data,
inputMethod. textInput
17.8.
DOM keydown, keyup keypress,
key char .
. , ,
key char .
key Enter, Delete Left,
. char null,
, , Tab,
, , .
key char,
17.8 key, .

17.1.3. HTML5
HTML5 API
- (22). API .
HTML5 -
.
.
.
HTML
<audio> <video> - .
,
,
:
canplay loadeddata playing stalled
canplaythrough loadedmetadata progress suspend
durationchange loadstart ratechange timeupdate
emptied pause seeked volumechange
ended play seeking waiting

, ,
, .
target <audio> <video>,
. ,
21.2.
(drag-and-drop),
HTML5, JavaScript
, ,
, .
:
dragstart drag dragend
dragenter dragover dragleave
drop

17.1.

487

, ,
.
dataTransfer, DataTransfer
, .
drag-and-drop, HTML5,
17.7.
HTML5
(22.2), -
Back () Forward ().
hashchange popstate, ,
load unload, Window, .
HTML5 HTML-.
, , HTML5
, invalid,
, .
, Opera,
, .
HTML5 -,
( 20.4),
, ,
(,
). ,
offline online: Window,
. ,
,
:
cached checking downloading error
noupdate obsolete progress updateready

message API -
.
(22.3)
.

(13.6.2). Window
, , message. ,
, data,
, source origin,
. message
Web Workers (22.4)
, Server-Sent Events
(18.3) WebSockets (22.9).
HTML5
, , ,
. 2 XMLHttpRequest,
File API ,
/.
XMLHttpRequest FileReader.

488

17.

loadstart, progress
loadend. , load, error
abort,
loadend. 18.1.4 22.6.5.
, HTML5
. Web Storage API (
20.1) storage ( Window),
. HTML5
beforeprint afterprint, Microsoft
IE. , Window
, ,
,
. (
, CSS
.)

17.1.4. ,

,
, .

, click scroll.

, ,
.
, Safari,
iPhone iPad Apple, orientation
change, , .
,
W3C Touch Events Specification,
,
Apple. ,
Apple Developer Center
(http://developer.apple.com/).
Safari
. gesturestart ,
, gestureend .
gesturechange,
. ,
, scale rotation. scale
.
, , scale 1.0,
, , scale 1.0.
rotation gesture
start.
.

17.2.

489

,
, .
.
, touchstart.
, touchmove.
, touchend. ,

. ,
, changedTouches. ,
, .
orientationchanged Window ,

. , orientationchan
ged, . Safari
Window orientation,
0, 90, 180 90.

17.2.
. ,
,
, .
, ,
. ,
.
JavaScript ,
HTML.

addEventListener(), , IE 8
, , attachEvent(),
IE IE9.

17.2.1.
,

. ,
on, : onclick, onchange, onload,
onmouseover .. ,
,
( readystatechange).
:
// onload Window.
// - : , .
window.onload = function() {
// <form>
var elt = document.getElementById("shipping_address");
// ,
// .

490

17.

elt.onsubmit = function() { return validate(this); }


}


. ,
, ,
,
.
,
,
.

( addEventListener()),
.

17.2.2.

, HTML-.
Java
Script.
, .
HTML
function. :
<button onclick="alert('');"> </button>

HTML- Java
Script-,
.
, . Java
Script Window. HTML
<body>, Window.
,
HTML5:
onafterprint onfocus ononline onresize
onbeforeprint onhashchange onpagehide onstorage
onbeforeunload onload onpageshow onundo
onblur onmessage onpopstate onunload
onerror onoffline onredo

HTML
JavaScript,
, :
function(event) {
with(document) {
with(this.form || {}) {
with(this) {
/* */
}

17.2.

491

}
}
}

ES5,
(5.7.3). event with,
17.3.
HTML
JavaScript. ,
, (, , ) HTML ,
JavaScript HTML.

17.2.3. addEventListener()
, , IE
8 ,
Window Document Elements
addEventListener(),
. addEventListener()
. , .
( ) on,
.
addEventListener() ,
. addEvent
Listener() .
false. true,

.
17.3.6. ,
,
false,
.
click
<button>. :
<button id="mybutton"> </button>
<script>
var b = document.getElementById("mybutton");
b.onclick = function() { alert(", !"); };
b.addEventListener("click", function() { alert(" !"); }, false);
</script>

addEventListener() click
onclick. , ,
alert(). , addEvent
Listener()
-
. ,
, .
addEventListener()

492

17.

-
.
addEventListener() removeEventListener(),
, , -
. ,
, - . ,
mousedown
mousemove mouseup,
, ,
mouseup .
, :
document.removeEventListener("mousemove", handleMouseMove, true);
document.removeEventListener("mouseup", handleMouseUp, true);

17.2.4. attachEvent()
Internet Explorer IE9 addEventListener()
removeEventListener(). IE5 , attach
Event() detachEvent().
attachEvent() detachEvent() add
EventListener() removeEventListener() :
IE , at
tachEvent() detachEvent() :
.
IE
on, . , attach
Event() onclick, addEventListener()
click.
attachEvent()
.
,
.
,
addEventListener() , ,
attachEvent() :
var b = document.getElementById("mybutton");
var handler = function() { alert("!"); };
if (b.addEventListener)
b.addEventListener("click", handler, false);
else if (b.attachEvent)
b.attachEvent("onclick", handler);

17.3.
-
, .
,

17.3.

493

, ( this),
. ,
IE 8 .
, , ,
, :

.

17.3.1.
( ,
)
. .
type, , . 17.1

.
IE 8 ,
, .
window.event.
, ,
window.event :
function handler(event) {
event = event || window.event;
//
}

,
attachEvent(), window.
event.
17.2.2 ,
HTML-
JavaScript . , IE,
event. IE , .
event,
window.event. ,
HTML, , event.

17.3.2.
,
:
e.onclick = function() { /* */ };

, (
, IE, )
, .
this .
this ,
addEventListener(). ,

494

17.

, attachEvent(): ,
attachEvent(), ,
this (Window) .
:
/*
*
* . , .
*/
function addEvent(target, type, handler) {
if (target.addEventListener)
target.addEventListener(type, handler, false);
else
target.attachEvent("on" + type,
function(event) {
// ,
//
return handler.call(target, event);
});
}

, ,
, , -,
attachEvent(), ,
detachEvent().

17.3.3.
JavaScript,
. ,
, , ,
. (, ,
addEvent(), .)
,
HTML-. ,
.

. , HTML-
, ,
<form> ( ) Document,
. 17.2.2 , HTML-
,
, with.
HTML-
,
. tagName this.tagName, getElementById
document.getElementById, ,
<form>,
id, , , zipcode this.form.zipcode.
,
, HTML-,

17.3.

495

,
. , Document
( ) open(), ,
HTML-, open() Window,
window.open(), open().
( ) ,
id
(15.9.1). , ,
location id, ,
HTML-, window.lo
cation location, Location .

17.3.4.
, ,
HTML-, .
false ,
, . ,
onclick false,
. ( ,
.)
onkeypress , false
. ( 17.6
.)
, onbeforeunload Win
dow. ,
. ,
, .
, ,
,
. , , add
EventListener() attachEvent() prevent
Default() returnValue .

17.3.5.

.
,
:
,
HTML-, .
, add
EventListener(), .1
1

DOM Level2 ,
,
DOM Level3 .

496

17.

, attachEvent(),

,
- .

17.3.6.
Window -
( XMLHttpRequest),
.
Document Element ,
.
, ,
DOM.
.
, .
, Document Window.

, :
-
. ,
change ,
<form>.
,
. focus, blur
scroll. load, , ,
Document Window.
load Window , .
.
.
. ,
addEventListener() ,
. true,

.
, IE, , ,
(
). , ,
, addEventListener(),
true. ,
IE 8 ,
.
,
.
Window,
Document, body , DOM,

. ,
, .

17.3.

497

,
.
,
, ,
.
,
, ,
. 17.2.

17.3.7.
17.3.4 , , ,
, ,
. ,
addEventListener(),
preventDefault() . IE,
8 , returnValue
false.
, :
function cancelHandler(event) {
var event = event || window.event; // IE
/* */
// ,
if (event.preventDefault) event.preventDefault(); //
if (event.returnValue) event.returnValue = false; // IE
return false; // ,
}

DOM Events Event


defaultPrevented. ,
, false
true preventDefault().1
, ,
.
. , addEventListener(),
stopPropagation(),
.
,
,
stopPropagation(). stopPropagation()
.
, , .
IE 8 stopPropagation() .
IE cancelBubble.
true . (IE 8
1

, jQuery (19),
defaultPrevented().

498

17.

,
.)
DOM Events Event
stopImmediatePropagation(). stopPropa
gation(),
. ,
, .
stopImmediatePropagation() .
, jQuery YUI, , ,
stopImmediatePropagation().

17.4.
, Java
Script, ,
. ,
.
- , -
,
. load Window,
13, 13.5
onLoad(). load
,
.
, .
-,
, load.
DOMContentLoaded ,
, ,
. async
,
. ( 13.3.1.)
Firefox
, Microsoft,
IE9. DOM ,
DOM Level3 Events,
HTML5.
13.3.4,
document.readyState. IE
readystatechange Document,
IE
complete. HTML5 readystate
change, load,
, readysta
techange load.
17.1 whenReady(),
onLoad() 13.5. , whenReady(),

17.4.

499

( Document) ,
. onLoad(),
whenReady() DOMContentLoaded readystatechan
ge load ,
,
. whenReady() ,
( ).
17.1. ,
/*
* whenReady() , (
* ),
* .
* DOMContentLoaded, readystatechange load.
* ,
* whenReady() , .
*/
var whenReady = (function() { // whenReady()
var funcs = []; // ,
var ready = false; // true handler
// , ,
//
function handler(e) {
// ,
if (ready) return;
// readystatechange ,
// "complete", ,
if (e.type==="readystatechange" && document.readyState !== "complete")
return;
// .
// ,
// funcs.length,
// .
for(var i = 0; i < funcs.length; i++)
funcs[i].call(document);
// ready true
//
ready = true;
funcs = null;
}
// handler
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", handler, false);
document.addEventListener("readystatechange", handler, false);
window.addEventListener("load", handler, false);
}
else if (document.attachEvent) {
document.attachEvent("onreadystatechange", handler);
window.attachEvent("onload", handler);
}

500

17.

// whenReady
return function whenReady(f) {
if (ready) f.call(document); // ,
else funcs.push(f); // ,
} // .
}());

17.5.
. .17.1.
, mouseenter mouseleave, .
click, ,
, .
contextmenu
, ,
.
17.1.

click

, ,
.

contextmenu , .
,
click.
dblclick

, .

mousedown

, .

mouseup

, .

mousemove

, .

mouseover

, .
relatedTarget ( fromElement IE) ,
.

mouseout

, . related
Target ( toElement IE) ,
.

mouseenter

mouseover, . IE
HTML5, .

mouseleave

mouseout, . IE
HTML5, .

, , clientX
clientY, .
,
( 15.8).
altKey, ctrlKey, metaKey shiftKey
-,
:
Shift, .

17.5.

501

button ,
.
, .
Event .
click .
, ,
mousedown mouseup. contextmenu
, , ,
,
.
, ,
, ,
. Event
.
17.2 drag(),
mousedown
. drag()
, DOM IE.
drag() . .
, mousedown,
(,
, ,
, ).
, CSS- posi
tion. , mousedown.
drag().
<img>,
Shift:
<img src="draggable.gif"
style="position:absolute; left:100px; top:100px;"
onmousedown="if (event.shiftKey) drag(this, event);">

drag() mousedown
,
.
getScrollOffsets() 15.8. drag()
mousemove mouseup, mou
sedown. mousemove
, mouseup
mousemove.
, mousemove mouseup
. ,
,
, mousemove
.
.
, IE, ,
setCapture(),

502

17.

. ,
.
, , moveHandler() upHandler()
drag(). ,
,
drag(), .
17.2.
/**
* Drag.js: HTML-.
*
* drag(),
* onmousedown. mousemove
* . mouseup .
* , IE.
* getScrollOffsets(), .
*
* :
*
* elementToDrag: , mousedown .
* . style.left
* style.top .
*
* event: Event, mousedown.
**/
function drag(elementToDrag, event) {
//
var scroll = getScrollOffsets(); // ,
// -
var startX = event.clientX + scroll.x;
var startY = event.clientY + scroll.y;
// ( ) ,
// . elementToDrag ,
// , offsetParent .
var origX = elementToDrag.offsetLeft;
var origY = elementToDrag.offsetTop;
// mousedown .
// .
var deltaX = startX - origX;
var deltaY = startY - origY;
// mousemove mouseup,
// mousedown.
if (document.addEventListener) { //
//
document.addEventListener("mousemove", moveHandler, true);
document.addEventListener("mouseup", upHandler, true);
}
else if (document.attachEvent) { // IE IE5-8
// IE
// setCapture() .
elementToDrag.setCapture();

17.5.
elementToDrag.attachEvent("onmousemove", moveHandler);
elementToDrag.attachEvent("onmouseup", upHandler);
// mouseup
elementToDrag.attachEvent("onlosecapture", upHandler);
}
//
if (event.stopPropagation) event.stopPropagation(); //
else event.cancelBubble = true; // IE
// , .
if (event.preventDefault) event.preventDefault(); //
else event.returnValue = false; // IE
/**
* mousemove,
* . .
**/
function moveHandler(e) {
if (!e) e = window.event; // IE

//
// .
var scroll = getScrollOffsets();
elementToDrag.style.left = (e.clientX + scroll.x - deltaX) + "px";
elementToDrag.style.top = (e.clientY + scroll.y - deltaY) + "px";
// .
if (e.stopPropagation) e.stopPropagation(); //
else e.cancelBubble = true; // IE
}
/**
* mouseup,
* .
**/
function upHandler(e) {
if (!e) e = window.event; // IE

// .
if (document.removeEventListener) { // DOM
document.removeEventListener("mouseup", upHandler, true);
document.removeEventListener("mousemove", moveHandler, true);
}
else if (document.detachEvent) { // IE 5+
elementToDrag.detachEvent("onlosecapture", upHandler);
elementToDrag.detachEvent("onmouseup", upHandler);
elementToDrag.detachEvent("onmousemove", moveHandler);
elementToDrag.releaseCapture();
}
// .
if (e.stopPropagation) e.stopPropagation(); //
else e.cancelBubble = true; // IE
}
}

503

504

17.

drag()
HTML- ( 16.2
):
<script src="getScrollOffsets.js"></script> <!-- drag()-->
<script src="Drag.js"></script> <!-- drag() -->
<!-- -->
<div style="position:absolute; left:100px; top:100px; width:250px;
background-color: white; border: solid black;">
<!-- "" . onmousedown. -->
<div style="background-color: gray; border-bottom: dotted black;
padding: 3px; font-family: sans-serif; font-weight: bold;"
onmousedown="drag(this.parentNode, event);">
<!-- -->
</div>
<!-- -->
<p> . , , .</p><p></p><p></p>
</div>

onmousedown <div>.
, this.parentNode.
, .

17.6.

mousewheel, .
,
mousewheel,
.
, mouse
wheel, ,
. , Fire
fox, mousewheel. Firefox
DOMMouseScroll. DOM Level3 Events
wheel mousewheel.
,
, . ,
,
.
, , ( Apple)
(
(trackball)). DOM Level3
,
/ /.
, mousewheel,
wheelDelta, .
120,
120. Safari Chrome
Apple, ,

17.6.

505

, wheelDelta
wheelDeltaX wheelDeltaY, wheelDelta
wheelDeltaY .
Firefox mousewheel
DOMMouseScroll detail
wheelDelta. detail wheel
Delta: , wheelDelta,
detail 40.
DOM Level3 Events
wheel
mousewheel DOMMouseScroll. , ,
wheel, deltaX, deltaY
deltaZ, .
120,
mousewheel.

: -
.
17.3 ,
. enclose(),

( )
,
. enclose()
, :
<script src="whenReady.js"></script>
<script src="Enclose.js"></script>
<script>
whenReady(function() {
enclose(document.getElementById("content"),400,200,-200,-300);
});
</script>
<style>div.enclosure { border: solid black 10px; margin: 10px; }</style>
<img id="content" src="testimage.jpg"/>

17.3
(13.4.5).
DOM Level3 Events ,
wheel,
.1 ,
DOMMouseScroll, Firefox
wheel mousewheel. , 17.3

CSS,
15.8 16.2.1.
1

:
, ,
.

506

17.

17.3. mousewheel
// ,
// ( 50 x 50). contentX
// contentY .
// ( <= 0.) mousewheel,
// .
function enclose(content, framewidth, frameheight, contentX, contentY) {
// :
// , mousewheel.
framewidth = Math.max(framewidth, 50);
frameheight = Math.max(frameheight, 50);
contentX = Math.min(contentX, 0) || 0;
contentY = Math.min(contentY, 0) || 0;
// CSS
var frame = document.createElement("div");
frame.className = "enclosure"; //
//
frame.style.width = framewidth + "px"; // .
frame.style.height = frameheight + "px";
frame.style.overflow = "hidden"; //
frame.style.boxSizing = "border-box"; // border-box
frame.style.webkitBoxSizing = "border-box"; //
frame.style.MozBoxSizing = "border-box"; // .
// elt.
content.parentNode.insertBefore(frame, content);
frame.appendChild(content);
//
content.style.position = "relative";
content.style.left = contentX + "px";
content.style.top = contentY + "px";
//
var isMacWebkit = (navigator.userAgent.indexOf("Macintosh") !== -1 &&
navigator.userAgent.indexOf("WebKit") !== -1);
var isFirefox = (navigator.userAgent.indexOf("Gecko") !== -1);
// mousewheel.
frame.onwheel = wheelHandler; //
frame.onmousewheel = wheelHandler; //
if (isFirefox) // Firefox
frame.addEventListener("DOMMouseScroll", wheelHandler, false);
function wheelHandler(event) {
var e = event || window.event; // , IE
// ,
// wheel, mousewheel (, 2- 1- )
// DOMMouseScroll Firefox. ,
// 30 . -
// , "wheel" "mousewheel",
// . ,
// wheel mousewheel.
var deltaX = e.deltaX*-30 || // wheel

507

17.6.
e.wheelDeltaX/4 || //
0; //
var deltaY = e.deltaY*-30 || //
e.wheelDeltaY/4 || //
(e.wheelDeltaY===undefined && //
e.wheelDelta/4) || //
e.detail*-10 || //
0; //

mousewheel

wheel
mousewheel Webkit
2- ,
1-
DOMMouseScroll Firefox

// 120
// . , Apple
// , delta
// 120, , Apple Mouse.
// , .
if (isMacWebkit) {
deltaX /= 30;
deltaY /= 30;
}
// - mousewheel wheel (
// ) Firefox, DOMMouseScroll.
if (isFirefox && e.type !== "DOMMouseScroll")
frame.removeEventListener("DOMMouseScroll", wheelHandler, false);
//
var contentbox = content.getBoundingClientRect();
var contentwidth = contentbox.right - contentbox.left;
var contentheight = contentbox.bottom - contentbox.top;
// Alt,
if (e.altKey) {
if (deltaX) {
framewidth -= deltaX; // , ,
framewidth = Math.min(framwidth, contentwidth); //
framewidth = Math.max(framewidth,50); //
frame.style.width = framewidth + "px"; // 50
}
if (deltaY) {
frameheight -= deltaY; //
frameheight = Math.min(frameheight, contentheight);
frameheight = Math.max(frameheight-deltaY, 50);
frame.style.height = frameheight + "px";
}
}
else { // Alt ,
if (deltaX) {
// ,
var minoffset = Math.min(framewidth-contentwidth, 0);
// deltaX contentX, , minoffset
contentX = Math.max(contentX + deltaX, minoffset);
contentX = Math.min(contentX, 0); // 0
content.style.left = contentX + "px"; //
}
if (deltaY) {
var minoffset = Math.min(frameheight - contentheight, 0);
// deltaY contentY, , minoffset

508

17.

contentY = Math.max(contentY + deltaY, minoffset);


contentY = Math.min(contentY, 0); // 0
content.style.top = contentY + "px"; // .
}
}
// .
// .
// . , preventDefault() wheel
// mousewheel.
if (e.preventDefault) e.preventDefault();
if (e.stopPropagation) e.stopPropagation();
e.cancelBubble = true; // IE
e.returnValue = false; // IE
return false;
}
}

17.7.
(drag-and-drop)
17.2 ,
. -
, . (drag-and-drop,
DnD) ,
,
. (DnD)
,
, ,
:
,
.
,
, ,
,
( -)
.

, .

.
Microsoft
IE.
, ,
HTML5 API,
IE, , API
. ,
API ,

17.7. (drag-and-drop)

509

IE,
HTML5.
IE
,
API .
-
.
. -,
. URL-
, ,
. , ,
, ,
, ,
.
, JavaScript API
:
, .
, ,
dataTransfer. DataTrans
fer,
.
, , ,
.
, HTML- draggable.
-,
, dragstart.
dataTransfer.setData(),
( ), . (
HTML5 API, dataTransfer.items.
add().) dataTransfer.
effectAllowed, ,
, , ,
dataTransfer.setDragImage() dataTransfer.addElement() (
, ),
,
.
drag.

,
drag.
, dragend.
, dataTransfer.
dropEffect, ,
. , , ,
.
dragstart ,
.

510

17.

17.4. hh:mm
<span> . ,
,
.
, draggable
true - ondragstart.
dataTransfer.setData(),
( ,
). dataTransfer.setDragIcon(),
( ),
.
17.4.
<script src="whenReady.js"></script>
<script>
whenReady(function() {
var clock = document.getElementById("clock"); //
var icon = new Image(); //
icon.src = "clock-icon.png"; // URL-
//
function displayTime() {
var now = new Date(); //
var hrs = now.getHours(), mins = now.getMinutes();
if (mins < 10) mins = "0" + mins;
clock.innerHTML = hrs + ":" + mins; //
setTimeout(displayTime, 60000); // 1
}
displayTime();
// .
// HTML-:
// <span draggable="true">...
clock.draggable = true;
//
clock.ondragstart = function(event) {
var event = event || window.event; // IE
// dataTransfer drag-and-drop API
var dt = event.dataTransfer;
// , .
// Date() ,
//
dt.setData("Text", Date() + "\n");
//
//
//
if
};
});
</script>
<style>

,
, , .
.
(dt.setDragImage) dt.setDragImage(icon, 0, 0);

17.7. (drag-and-drop)

511

#clock { /* */
font: bold 24pt sans; background: #ddf; padding: 10px;
border: solid black 2px; border-radius: 10px;
}
</style>
<h1>Drag timestamps from the clock</h1>
<span id="clock"></span> <!-- -->
<textarea cols=60 rows=20></textarea> <!-- -->

, .
: ,
HTML-, ,
. (
,
HTML5, , ,
- dropzone.)
.
, dragenter.
, , ,
dataTransfer.types. (
dataTransfer.effectAllowed, ,
: ,
.)
- ,
.
. :
, , .
dragenter, ,

.
dragenter, dragover,
. () ,
, ,
- .
, ,
, dataTransfer.dropEffect
dragover.
,
,
dragleave.

, dragenter. ,
, dragenter dragleave, ;
, , dragleave ,
-
.
, ,
drop.
dataTransfer.getData()

512

17.

.
, dataTransfer.files ,
, File. (
18.11.) HTML5 API drop
dataTransfer.items[],
, .
17.5 , <ul>
<li> .
JavaScript.
<ul>, class dnd,
.
: , ,
.

.

, . (
,
.)
17.5.
/*
* ,
* .
* , ,
* .
* , .
*/
whenReady(function() { // ,
// <ul class='dnd'> dnd()
var lists = document.getElementsByTagName("ul");
var regexp = /\bdnd\b/;
for(var i = 0; i < lists.length; i++)
if (regexp.test(lists[i].className)) dnd(lists[i]);
//
function dnd(list) {
var original_class = list.className; // CSS-class
var entered = 0; //
// , .
// , ,
// , , , ,
// . -,
// , .
list.ondragenter = function(e) {
e = e || window.event; // , IE
var from = e.relatedTarget;
// dragenter dragleave , - ,
// , ,
// , <ui> <li>.

17.7. (drag-and-drop)

513

// , relatedTarget, .
// /.

// , - ,
// ,
entered++;
if ((from && !ischild(from, list)) || entered == 1) {
// dataTransfer
var dt = e.dataTransfer;
// dt.types , ,
// . HTML5 , types
// contains().
// indexOf. IE 8 .
var types = dt.types; //
//
// , , ,
// , false, .
if (!types || // IE
(types.contains && types.contains("text/plain")) || //HTML5
(types.indexOf && types.indexOf("text/plain")!=-1)) //Webkit
{
list.className = original_class + " droppable";
return false;
}
// ,
return; //
}
return false; // , -
};
// .
// , false,
// .
list.ondragover = function(e) { return false; };
// ,
// .
// ( ),
// .
list.ondragleave = function(e) {
e = e || window.event;
var to = e.relatedTarget;
//
// ,
entered--;
if ((to && !ischild(to,list)) || entered <= 0) {
list.className = original_class;
entered = 0;
}
return false;
};
// , .

514

17.

// <li>
list.ondrop = function(e) {
e = e || window.event; //
// .
// "Text" - "text/plain".
// IE "text/plain", "Text".
var dt = e.dataTransfer; // dataTransfer
var text = dt.getData("Text"); // .
// ,
// .
if (text) {
var item = document.createElement("li"); // <li>
item.draggable = true; //
item.appendChild(document.createTextNode(text)); //
list.appendChild(item); //
// entered
list.className = original_class;
entered = 0;
return false;
}
};
//
var items = list.getElementsByTagName("li");
for(var i = 0; i < items.length; i++)
items[i].draggable = true;
// .
// , ,
// .
// , .
list.ondragstart = function(e) {
var e = e || window.event;
var target = e.target || e.srcElement;
// , <li>,
if (target.tagName !== "LI") return false;
// dataTransfer
var dt = e.dataTransfer;
//
dt.setData("Text", target.innerText || target.textContent);
// ,
dt.effectAllowed = "copyMove";
};
//
list.ondragend = function(e) {
e = e || window.event;
var target = e.target || e.srcElement;
// , .
// IE8 "none",
// "move" ondrop .

17.8.

515

// "move" IE
//
// .
if (e.dataTransfer.dropEffect === "move")
target.parentNode.removeChild(target);
}
// , ondragenter ondragleave.
// true, a b.
function ischild(a,b) {
for(; a; a = a.parentNode) if (a === b) return true;
return false;
}
}
});

17.8.
. key
down keyup
. keypress ,
, . DOM
Level3 Events textinput,
, , (
, ,
,
).
textinput ,
Webkit textInput (
I).
textinput
textInput , data,
. ( , in
putMethod, , .)
data
,
.
, keypress,
. keypress .

, ,
String.fromCharCode().
keyCode .
Firefox charCode.
keypress .
Firefox keypress
. (
), , charCode
0.

516

17.

textinput, textInput keypress ,


.
. , ,
. 17.6
JavaScript, .
<input type=text> () data-allo
wed-chars. textinput, textInput key
press
, data-allowed-chars.
17.6 HTML, .
17.6.
/**
* InputFilter.js: <input>
*
* <input type="text"> ,
* "data-allowed-chars". keypress, textInput
* textinput , ,
* , . <input>
* "data-messageid", id
* . ,
* id . ,
* .
* , .
* CSS , .
*
* HTML, .
* Zipcode: <input id="zip" type="text"
* data-allowed-chars="0123456789" data-messageid="zipwarn">
* <span id="zipwarn" style="color:red;visibility:hidden"> </span>
*
* :
* .
*/
whenReady(function () { // ,
// <input>
var inputelts = document.getElementsByTagName("input");
//
for(var i = 0 ; i < inputelts.length; i++) {
var elt = inputelts[i];
// ,
// data-allowed-chars.
if (elt.type != "text" || !elt.getAttribute("data-allowed-chars"))
continue;
// input
// keypress - .
// textInput ( ) Safari
// Chrome 2010 .
// textinput ( ) -
// "DOM Level 3 Events".
if (elt.addEventListener) {
elt.addEventListener("keypress", filter, false);

17.8.

517

elt.addEventListener("textInput", filter, false);


elt.addEventListener("textinput", filter, false);
}
// textinput IE,
// addEventListener()
else {
elt.attachEvent("onkeypress", filter);
}
}
// keypress textInput,
function filter(event) {
// target
var e = event || window.event; // IE
var target = e.target || e.srcElement; // IE
var text = null; //
//
if (e.type === "textinput" || e.type === "textInput") text = e.data;
else { // keypress
// Firefox charCode
var code = e.charCode || e.keyCode;
// - ,
if (code < 32 || // ASCII
e.charCode == 0 || // (Firefox)
e.ctrlKey || e.altKey) // -
return; //
//
var text = String.fromCharCode(code);
}
// input
var allowed = target.getAttribute("data-allowed-chars"); //
var messageid = target.getAttribute("data-messageid"); // id
if (messageid) // id,
var messageElement = document.getElementById(messageid);
//
for(var i = 0; i < text.length; i++) {
var c = text.charAt(i);
if (allowed.indexOf(c) == -1) { // ?
// ,
if (messageElement) messageElement.style.visibility="visible";
// ,
if (e.preventDefault) e.preventDefault();
if (e.returnValue) e.returnValue = false;
return false;
}
}
// ,
// , .
if (messageElement) messageElement.style.visibility = "hidden";
}
});

518

17.

keypress textinput
, ,
,
. input,
.

, . ,
, ,
input, :
SURNAME: <input type="text" oninput="this.value = this.value.toUpperCase();">

input HTML5
, IE. IE ,
value
propertychange. 17.7
,
.
17.7. propertychange

function forceToUpperCase(element) {
if (typeof element === "string") element=document.getElementById(element);
element.oninput = upcase;
element.onpropertychange = upcaseOnPropertyChange;
// : input
function upcase(event) { this.value = this.value.toUpperCase(); }
// : propertychange
function upcaseOnPropertyChange(event) {
var e = event || window.event;
// value
if (e.propertyName === "value") {
// onpropertychange,
this.onpropertychange = null;
//
this.value = this.value.toUpperCase();
// propertychange
this.onpropertychange = upcaseOnPropertyChange;
}
}
}

17.9.
keydown keyup ,
. -
, - .
,
, keydown,
keyup.

17.9.

519

, , keyCode
, . ,
, keyCode
, ,
. keyCode,
, Shift,
.
keyCode,
, ,
Shift, . ,
, keyCode
. keyCode .
,
. 17.8,
keyCode .
,
altKey, ctrlKey, metaKey shiftKey, true,
-
.
keydown keyup, keyCode
, . DOM Level3
Events keydown keyup ,
keyCode. key,
.
, key .
key ,
F2, Home Left.
key, DOM
Level3 Events, .
Webkit, Safari Chrome
keyIdentifier. , key,
keyIdentifier , ,
Shift Enter. , ,

. , A
U+0041.
17.8 Keymap,
, PageUp, Alt_Z ctrl+alt+shift+F5
JavaScript, .
Keymap()
JavaScript,
, -.
bind()
unbind(). Keymap HTML- ( Docu
ment) install(). Keymap
keydown. ,
, ,
. , . key

520

17.

down key, DOM Level3 Events,


. Webkit-
keyIdentifier. ,
keyCode. 17.8 ,
.
17.8. Keymap
/*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*

Keymap.js: -.
Keymap.
( )
-. Keymap HTML-
keydown. , Keymap
.
Keymap JavaScript-,
.
, -.
Keymap ,
- bind().
, unbind().
Keymap, install(),
HTML-, document. install()
onkeydown. ,
- ( ),
. Keymap
HTML-.

,
,
-. ,
. : "A", "7", "F2", "PageUp",
"Left", "Backspace" "Esc".
Keymap.keyCodeToKeyName, .
, "DOM Level 3".
, key, .
-.
Alt, Ctrl, Meta Shift.
,
+. : "SHIFT+A", "Alt_F2", "meta-v" "ctrl alt left".
Mac Meta Command, Alt
Option. Windows Meta.
-
document ,
, Keymap,

17.9.

521

* :
* 1) keydown
* 2)
* , ,
* keydown. - false,
* Keymap
* , keydown.
*
*
*
* - .
* (, Alt-F4).
* (, Ctrl-S).
* , .
* ,
* - . -
* Ctrl Alt .
*
* , ,
* Shift (`=[];',./\)
* US.
* , .
*/
// -
function Keymap(bindings) {
this.map = {}; // ->
if (bindings) { //
for(name in bindings) this.bind(name, bindings[name]);
}
}
// -
Keymap.prototype.bind = function(key, func) {
this.map[Keymap.normalize(key)] = func;
};
//
Keymap.prototype.unbind = function(key) {
delete this.map[Keymap.normalize(key)];
};
// Keymap HTML-
Keymap.prototype.install = function(element) {
var keymap = this;
// -
function handler(event) { return keymap.dispatch(event, element); }
//
if (element.addEventListener)
element.addEventListener("keydown", handler, false);
else if (element.attachEvent)
element.attachEvent("onkeydown", handler);
};
// , .
Keymap.prototype.dispatch = function(event, element) {

522

17.

// -,
var modifiers = ""
var keyname = null;
//
//
if
if
if
if


, .
(event.altKey) modifiers += "alt_";
(event.ctrlKey) modifiers += "ctrl_";
(event.metaKey) modifiers += "meta_";
(event.shiftKey) modifiers += "shift_";

// , key,
// DOM Level 3:
if (event.key) keyname = event.key;
// Safari Chrome
// keyIdentifier
else if(event.keyIdentifier&&event.keyIdentifier.substring(0,2) !== "U+")
keyname = event.keyIdentifier;
// keyCode ->
else keyname = Keymap.keyCodeToKeyName[event.keyCode];
// ,
// .
if (!keyname) return;
//
//
var keyid = modifiers + keyname.toLowerCase();
// ,
var handler = this.map[keyid];
if (handler) { // ,
// -
var retval = handler.call(element, event, keyid);
// false,
//
if (retval === false) {
if (event.stopPropagation) event.stopPropagation(); // DOM
else event.cancelBubble = true; // IE
if (event.preventDefault) event.preventDefault(); // DOM
else event.returnValue = false; // IE
}
// ,
return retval;
}
};
// .
// "meta" "ctrl",
// Meta-C "Command-C" Mac "Ctrl-C" .
Keymap.normalize = function(keyid) {
keyid = keyid.toLowerCase(); //
var words = keyid.split(/\s+|[\-+_]/); //
var keyname = words.pop(); // keyname -

523

17.9.
keyname = Keymap.aliases[keyname] || keyname; //
words.sort(); //
words.push(keyname); //
//
return words.join("_"); //
};
Keymap.aliases = { //
"escape":"esc", //
"delete":"del", //
"return":"enter", //
"ctrl":"control", //
"space":"spacebar",
"ins":"insert"
};


"" , DOM Level 3,
.

.

// keyCode keydown
// .
Keymap.keyCodeToKeyName = {
//
8:"Backspace", 9:"Tab", 13:"Enter", 16:"Shift", 17:"Control", 18:"Alt",
19:"Pause", 20:"CapsLock", 27:"Esc", 32:"Spacebar", 33:"PageUp",
34:"PageDown", 35:"End", 36:"Home", 37:"Left", 38:"Up", 39:"Right",
40:"Down", 45:"Insert", 46:"Del",
// ( )
48:"0",49:"1",50:"2",51:"3",52:"4",53:"5",54:"6",55:"7",56:"8",57:"9",
// . ,
//
65:"A", 66:"B", 67:"C", 68:"D", 69:"E", 70:"F", 71:"G", 72:"H", 73:"I",
74:"J", 75:"K", 76:"L", 77:"M", 78:"N", 79:"O", 80:"P", 81:"Q", 82:"R",
83:"S", 84:"T", 85:"U", 86:"V", 87:"W", 88:"X", 89:"Y", 90:"Z",
// .
// ( Opera.)
96:"0",97:"1",98:"2",99:"3",100:"4",101:"5",102:"6",103:"7",104:"8",
105:"9",106:"Multiply", 107:"Add", 109:"Subtract", 110:"Decimal",
111:"Divide",
//
112:"F1", 113:"F2", 114:"F3", 115:"F4", 116:"F5", 117:"F6",
118:"F7", 119:"F8", 120:"F9", 121:"F10", 122:"F11", 123:"F12",
124:"F13", 125:"F14", 126:"F15", 127:"F16", 128:"F17", 129:"F18",
130:"F19", 131:"F20", 132:"F21", 133:"F22", 134:"F23", 135:"F24",
// ,
// Shift.
// : FF
// , Subtract
59:";", 61:"=", 186:";", 187:"=", // Firefox Opera 59,61
188:",", 190:".", 191:"/", 192:"`", 219:"[", 220:"\\", 221:"]", 222:"'"
};

18
18.

HTTP

(Hypertext Transfer Protocol, HTTP) ,


- ,
- -
. , - HTTP.
, , HTTP,
, URL .
JavaScript- HTTP. HTTP-
, location
Window submit() Form.
.
HTTP -,
, .
JavaScript- -, .
Ajax -,
HTTP.1 Ajax-
HTTP
- .
(
) -,
. -
Ajax
1

Ajax Asynchronous JavaScript and XML ( JavaScript


XML). (Jesse James Garrett)
Ajax: A New Approach to Web Applications
2005 (http://www.adaptivepath.com/publications/essays/archives/000385.php) (
: http://galleo.
ru/articles/w160.). Ajax ,
, ,
-, HTTP-.

525

,
.
Comet -,
HTTP.1 Comet
Ajax: Comet ,
, . -
, ,
Ajax . Ajax
. Comet
. Comet Server Push, Ajax Push
HTTP Streaming.
Ajax Comet,
. <img>, ,
src. URL-,
HTTP- GET URL-.
, -,
URL- src
<img>. -
, , , :
11.2
<img> Ajax,
: ,
,
. <iframe> .
<iframe> Ajax
URL- , -,
URL- src <iframe>. HTML, , -,
<iframe>. <iframe>
, ,
CSS.
, <iframe>. ,
,
13.6.2.
src <script>
HTTP- GET. <script>
HTTP ,

. Ajax
1

Comet (Alex Russell) Comet: Low La


tency Data for the Browser (http://infrequently.org/2006/03/comet-low-latency-data-forthe-browser/). , , Ajax:
, Comet Ajax .

- (web bugs).
- ,
, , .
- -.

526

18. HTTP

<script> JSON (
6.9), ,
<script> JavaScript. -
JSON Ajax JSONP.
Ajax <iframe>
<script>, .
XMLHttpRequest,
HTTP.
POST- GET-
- ,
Document. , XMLHttpRequest
XML-
. XMLHttpRequest
18.1, .
Ajax
XMLHttpRequest, 18.2 ,
<script>,
.
Comet , Ajax,
(, )

,
. Comet , ,
<iframe>, <script>,
<iframe>.
Comet ,
( Ajax-),
, . ,
, ,
.
.
Comet
, -,
Comet, , -,
Dojo.
Server-Sent Events,
HTML5,
Comet EventSource.
EventSource 18.3
XMLHttpRequest.

Ajax Comet.
/ , , RPC
(Remote Procedure Call )
/.
,
Ajax Comet.

18.1. XMLHttpRequest

527

XML
X Ajax XML.
HTTP (XMLHttp
Request) XML , ,
, XMLHttpRequest responseXML.
, XML
HTTP. :
, XML .
, Ajax XML-,
XML ,
. XMLHttpRequest
, :
XMLHttpRequest
,
. -, ,
XML. -,
, HTTP HTTPS (
, HTTP HTTPS,
). ,
(requests) ,
HTTP. , ,
HTTP- HTTP-
HTTP-.

18.1. XMLHttpRequest
HTTP
XMLHttpRequest.
/,
. XMLHttpRequest ,
W3C.
W3C XMLHttpRequest Level2.
XMLHttpRequest,
XMLHttpRequest Level 2 (
XHR2), .
,
HTTP, , , XMLHttp
Request:
var request = new XMLHttpRequest();

XMLHttp
Request, ,
, .

528

18. HTTP

XMLHttpRequest IE6
XMLHttpRequest IE,
5. IE5 IE6
ActiveX-. XML
HttpRequest() IE7, ,
:
// XMLHttpRequest() IE5 IE6
if (window.XMLHttpRequest === undefined) {
window.XMLHttpRequest = function() {
try {
// ActiveX-,
return new ActiveXObject("Msxml2.XMLHTTP.6.0");
}
catch (e1) {
try {
//
return new ActiveXObject("Msxml2.XMLHTTP.3.0");
}
catch(e2) {
// -
throw new Error("XMLHttpRequest ");
}
}
};
}

HTTP- :
HTTP-
URL-
,


HTTP-, , :
, ,



, , ,
HTTP- HTTP-.
,
.
/ HTTP
. :
cookies;

18.1. XMLHttpRequest

529

; , ;
- .. XMLHttpRequest
,
. cookies, ,
-, .

XMLHttpRequest
URL- -
, HTML- ,
, -
. , ,
Ajax XMLHttpRequest.
XMLHttpRequest HTTP
HTTPS. ,
FTP, ,
,
HTTP. - ,
XMLHttpRequest
URL-,
file://, http://.
http://. (
18.1.6.) , , XMLHttpRequest,
- ( -).

18.1.1.
XMLHttpRequest
HTTP- open() XMLHttpRequest,
: URL:
request.open("GET", // HTTP GET
"data.csv"); // URL-

open() HTTP- .
, ,
, HTTP. GET
POST . GET
, URL-
. ,
. POST
HTML-.
( ),
( ). POST
URL , ,
, .

530

18. HTTP

GET POST, XMLHttpRequest


open() DELETE, HEAD, OPTIONS PUT
. ( HTTP CONNECT, TRACE TRACK
- .)
, HEAD, ,
,
18.13.
open() URL- .
URL- , ,
open(). ,
,
:
. ( XMLHttpRequest Level2
, 18.1.6.)
,
. POST, , ,
Content-Type, MIME- :
request.setRequestHeader("Content-Type", "text/plain");

setRequestHeader()
, : HTTP-
.
Content-Length, Date, Referer
User-Agent: XMLHttpRequest
. XMLHttpRequest
cookies ,
,
setRequestHeader() :
Accept-Charset Content-Transfer-Encoding TE
Accept-Encoding Date Trailer
Connection Expect Transfer-Encoding
Content-Length Host Upgrade
Cookie Keep-Alive User-Agent
Cookie2 Referer Via

Authorization,
. , ,
open() ,
XMLHttpRequest .
( open() ,
, ,
.)
HTTP- XML
HttpRequest .
send():
request.send(null);

GET- , null
. POST- ,

18.1. XMLHttpRequest

531

Content-Type,
setRequestHeader().
18.1 XMLHttpRequest,
. POST
, .
18.1. POST
function postMessage(msg) {
var request = new XMLHttpRequest(); //
request.open("POST", "/log.php"); // POST
//
request.setRequestHeader("Content-Type", // -
"text/plain;charset=UTF-8");
request.send(msg); // msg
// . .
}

, send() 18.1
: .
HTTP- ,
.


HTTP- :
URL- ,
, , .
XMLHttpRequest ,
send(). XMLHttpRequest ,
. ,
XMLHttpRequest ,
HTTP-. , setRequestHeader()
open() send(),
.

18.1.2.
HTTP- ,
. XMLHttpRequest:
status statusText HTTP
. HTTP-,
200 OK 404 Not Found
, .
getResponseHeader() get
AllResponseHeaders(). cookies XMLHttpRequest
: Cookie ,

532

18. HTTP

getAllResponseHeaders(), null,
Set-Cookie Set-Cookie2 getResponseHeader().
responseText
Document responseXML. (
:
XHTML- XML-, XHR2
, HTML-.)
responseXML 18.1.2.2.
XMLHttpRequest (
18.1.2.1): send()
, , ,
.
, readystatechange ( progress,
XHR2 18.1.4),
XMLHttpRequest. , ,
, readyState.
readyState ,
HTTP-; .18.1.
, , ,
XMLHttpRequest. XMLHttpRequest,
IE8 ,
, XMLHttpRequest.DONE
4.
readystatechange ,
readyState.
, readyState 0 1.
send(), , readyState -
OPENED.
LOADING, .
readystatechange,
readyState 4.
, readystatechange
readyState.
readystatechange,
onreadystatechange XMLHttpRequest.
addEventListener() ( attachEvent() IE 8
),
, onreadystatechange.
18.1. readyState XMLHttpRequest

UNSENT

open()

OPENED

open()

HEADERS_RECEIVED

LOADING

DONE

18.1. XMLHttpRequest

533

18.2 getText(),
readystatechange.
.
. Content-Type,
, .
, ( ) .
18.2. HTTP- onreadystatechange
// HTTP GET URL-.
// , ,
//
function getText(url, callback) {
var request = new XMLHttpRequest(); //
request.open("GET", url); // URL-
request.onreadystatechange = function() { //
//
if (request.readyState === 4 && request.status === 200) {
var type = request.getResponseHeader("Content-Type");
if (type.match(/^text/)) // ,
callback(request.responseText); //
}
};
request.send(null); //
}

18.1.2.1.
HTTP- .
XMLHttpRequest
. open() false,
send() .
:
send() , status
responseText XMLHttpRequest.
getText() 18.2:
// HTTP GET URL-.
// .
// .
function getTextSync(url) {
var request = new XMLHttpRequest(); //
request.open("GET", url, false); // false -
request.send(null); //
// , 200
if (request.status !== 200) throw new Error(request.statusText);
// ,
var type = request.getResponseHeader("Content-Type");
if (!type.match(/^text/))
throw new Error(" ; : " + type);
return request.responseText;
}

534

18. HTTP

,
. JavaScript
, send() ,
. ,
, ,
. 22.4 ,
.

18.1.2.2.
,
, MIME- text/plain, text/html text/css,
responseText XMLHttpRequest.
.
XML- XHTML-, XML responseXML.
Document, ,
15. ( XHR2 ,
text/html
responseXML Document,

.)

, ,
JSON (6.9). res
ponseText JSON.parse(). 18.3
18.2: GET URL-

.
Document, ,
JSON.parse(), .
18.3. HTTP-
// HTTP GET URL-.
//
// XML-, JSON .
function get(url, callback) {
var request = new XMLHttpRequest(); //
request.open("GET", url); // URL-
request.onreadystatechange = function() { //
//
if (request.readyState === 4 && request.status === 200) {
//
var type = request.getResponseHeader("Content-Type");
// ,
// HTML
if (type.indexOf("xml") !== -1 && request.responseXML)
callback(request.responseXML); // XML
else if (type === "application/json")
callback(JSON.parse(request.responseText)); // JSON
else

18.1. XMLHttpRequest

535

callback(request.responseText); //
}
};
request.send(null); //
}

18.3 Content-Type
application/json . ,
, application/Java
Script text/JavaScript. XMLHttpRequest
JavaScript
eval() (4.12.2). ,
<script> ,
. 13.4, ,
<script> HTTP- ,
XMLHttpRequest.
HTTP- - (
, ). responseText

, charCodeAt() .
XHR2 ,

. 22.6.2.
,
Content-Type MIME- . ,
, XML-, MIME, XMLHttpRequest
responseXML. ,
charset Content-Type, XMLHttpRequest
response
Text .
XHR2 overrideMimeType(),
, .
MIME-, -,
, send()
overrideMimeType() XMLHttpRequest
Content-Type . ,
XML-,
. overrideMimeType(),
XMLHttpRequest,
XML-:
// , XML-
request.overrideMimeType("text/plain; charset=utf-8")

18.1.3.
HTTP POST , ,
. 18.1
. HTTP-

536

18. HTTP

.
.

18.1.3.1. HTML-
HTML-. ,
( )
. HTML-
POST, .
:
URI- (
),
, / .
, :
find=pizza&zipcode=02134&radius=1km

MIME:
application/x-www-form-urlencoded

Content-Type
POST.
,
HTML-,
. Ajax-
JavaScript-, .
( HTML-,
.) , ,
JavaScript-:
{
find: "pizza",
zipcode: 02134,
radius: "1km"
}



,
, ,
. 18.4 ,
.
18.4. HTTP-
/**
* , /
* HTML-, application/x-www-form-urlencoded
*/
function encodeFormData(data) {
if (!data) return ""; //
var pairs = []; // /
for(var name in data) { //

18.1. XMLHttpRequest

537

if (!data.hasOwnProperty(name)) continue; // .
if (typeof data[name] === "function") continue;//
var value = data[name].toString(); // .
name = encodeURIComponent(name.replace("%20", "+")); //
value = encodeURIComponent(value.replace("%20", "+")); //
pairs.push(name + "=" + value); // /
}
return pairs.join('&'); // &
}

encodeFormData() ,
postData(), 18.5. ,
postData() (
) .
XMLHttpRequest .

.
18.5. HTTP POST

function postData(url, data, callback) {
var request = new XMLHttpRequest();
request.open("POST", url); // POST . url
request.onreadystatechange = function() { //
if (request.readyState === 4 && callback) //
callback(request); //
};
request.setRequestHeader("Content-Type", // "Content-Type"
"application/x-www-form-urlencoded");
request.send(encodeFormData(data)); //
} //

GET-,
, ,
GET , POST. GET-
,
URL ( ).
encodeFormData() GET-
, 18.6 .
18.6. GET-
function getData(url, data, callback) {
var request = new XMLHttpRequest();
request.open("GET", url + // GET url
"?" + encodeFormData(data)); //
request.onreadystatechange = function() { //
if (request.readyState === 4 && callback) callback(request);
};
request.send(null); //
}

URL- HTML-
, XMLHttpRequest .

538

18. HTTP


URL-,
:
http://restaurantfinder.example.com/02134/1km/pizza

18.1.3.2. JSON
POST-
,
HTTP.
JSON. 18.7
, JSON.stringify() (6.9)
. ,
18.5 .
18.7. HTTP POST JSON
function postJSON(url, data, callback) {
var request = new XMLHttpRequest();
request.open("POST", url); // POST . url
request.onreadystatechange = function() { //
if (request.readyState === 4 && callback) //
callback(request); //
};
request.setRequestHeader("Content-Type", "application/json");
request.send(JSON.stringify(data));
}

18.1.3.3. XML

XML.
JSON Java
Script-, XML-.
:
<query>
<find zipcode="02134" radius="1km">
pizza
</find>
</query>

, , send()
XMLHttpRequest null.
Document XML-. 18.8
, Document XML-
HTTP-.
18.8. HTTP POST XML-
// "", "" "" XML-
// URL-.
//
function postQuery(url, what, where, radius, callback) {

18.1. XMLHttpRequest

539

var request = new XMLHttpRequest();


request.open("POST", url); // POST url
request.onreadystatechange = function() { //
if (request.readyState === 4 && callback) callback(request);
};
// XML- <query>
var doc = document.implementation.createDocument("", "query", null);
var query = doc.documentElement; // <query>
var find = doc.createElement("find"); // <find>
query.appendChild(find); // <query>
find.setAttribute("zipcode", where); // <find>
find.setAttribute("radius", radius);
find.appendChild(doc.createTextNode(what)); // <find>
// XML .
// , Content-Type .
request.send(doc);
}

, 18.8 Content-Type
. send() XML-, XMLHttpRequest
Content-Type,
. , send()
Content-Type, XMLHttpRequest
text/plain; charset=UTF-8.
18.1 ,
.

18.1.3.4.
HTML- , ,
<input type="file">,
POST-. HTML-
,
XMLHttpRequest. ,
XHR2, File send().
File():
File, ,
. , File, <input ty
pe="file"> files, , ,
File. (drag-and-drop) (
17.7) ,
, dataTransfer.files drop.
File 22.6 22.7.
File
, send(). 18.9
JavaScript-, change
,
POST URL.

540

18. HTTP

18.9. HTTP POST


// <input type="file"> data-uploadto
// onchange,
// URL- "uploadto". .
whenReady(function() { //
var elts = document.getElementsByTagName("input"); // input
for(var i = 0; i < elts.length; i++) { //
var input = elts[i];
if (input.type !== "file") continue; // ,
//
var url = input.getAttribute("data-uploadto"); //
if (!url) continue; // url
input.addEventListener("change", function() { //
var file = this.files[0]; //
if (!file) return; // ,
var xhr = new XMLHttpRequest(); //
xhr.open("POST", url); // POST URL
xhr.send(file); //
}, false);
}
});

22.6, File
Blob. XHR2 send()
Blob. type Blob
Content-Type, .
, ,
Blob,
22.5 22.6.3, .

18.1.3.5. multipart/form-data
HTML-
,
, multi
part/form-data Content-Type.
, .
multipart/form-data ,
.
XHR2 FormData,
, .
FormData() FormData,
append() (
File Blob). FormData
send(). send() ,
, Content-Type . 18.10
FormData, 18.11.
18.10. multipart/form-data
function postFormData(url, data, callback) {
if (typeof FormData === "undefined")

18.1. XMLHttpRequest

541

throw new Error(" FormData ");


var request = new XMLHttpRequest(); // HTTP-
request.open("POST", url); // POST URL
request.onreadystatechange = function() { // .
if (request.readyState === 4 && callback) //
callback(request); // .
};
var formdata = new FormData();
for(var name in data) {
if (!data.hasOwnProperty(name)) continue; // . -
var value = data[name];
if (typeof value === "function") continue; //
// "" .
// File
formdata.append(name, value); // /,
} //
// / multipart/form-data. // . , send
// Content-Type, FormData
request.send(formdata);
}

18.1.4. ,
HTTP-
HTTP-
readystatechange. XHR2
, Firefox, Chrome Safari.
XMLHttpRequest
,
readyState.
, ,
. send(), load
start. XMLHttpRequest
progress, 50 ,
,
. , progress
. load.
,
load XMLHttpRequest,
, HTTP- 200 OK, 404 Not Found,
.
, HTTP- ,
.
, timeout.
, abort. (
abort() 18.1.5.) ,
,
, error.

542

18. HTTP


load, abort, timeout error. XHR2 ,
loadend .
loadend
.
,
, addEventListener() XMLHttpRequest.
,
,
, onprogress onload. ,
:
if ("onprogress" in (new XMLHttpRequest())) {
// , ,
}

, ,
, Event, type
timestamp, . loaded
, . total
() ,
Content-Length, 0, . ,
lengthComputable true,
, false . , total loaded
, :
request.onprogress = function(e) {
if (e.lengthComputable)
progress.innerHTML = Math.round(100*e.loaded/e.total) + "% ";
}

18.1.4.1. ,
, HTTP, XHR2
HTTP-. , ,
XMLHttpRequest upload. upload ,
addEventListener() -
, onprogress onload. (
onreadystatechange:
.)

,
. x XMLHttpRequest x.onprogress
. x.upload.onprog
ress .
18.11 , progress,
, .
, File
(drag-and-drop) FormData
XMLHttpRequest.

18.1. XMLHttpRequest

543

, ,
.
18.11.
// "fileDropTarget"
// DnD,
// .
// URL-, data-uploadto.
whenReady(function() {
var elts = document.getElementsByClassName("fileDropTarget");
for(var i = 0; i < elts.length; i++) {
var target = elts[i];
var url = target.getAttribute("data-uploadto");
if (!url) continue;
createFileUploadDropTarget(target, url);
}
function createFileUploadDropTarget(target, url) {
//
// .
// ,
// .
var uploading = false;
console.log(target, url);
target.ondragenter = function(e) {
console.log("dragenter");
if (uploading) return; // ,
//
var types = e.dataTransfer.types;
if (types &&
((types.contains && types.contains("Files")) ||
(types.indexOf && types.indexOf("Files") !== -1))) {
target.classList.add("wantdrop");
return false;
}
};
target.ondragover = function(e) { if (!uploading) return false; };
target.ondragleave = function(e) {
if (!uploading) target.classList.remove("wantdrop");
};
target.ondrop = function(e) {
if (uploading) return false;
var files = e.dataTransfer.files;
if (files && files.length) {
uploading = true;
var message = " :<ul>";
for(var i = 0; i < files.length; i++)
message += "<li>" + files[i].name + "</li>";
message += "</ul>";
target.innerHTML = message;
target.classList.remove("wantdrop");
target.classList.add("uploading");

544

18. HTTP

var xhr = new XMLHttpRequest();


xhr.open("POST", url);
var body = new FormData();
for(var i=0; i < files.length; i++) body.append(i, files[i]);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
target.innerHTML = message +
Math.round(e.loaded/e.total*100) +
"% ";
}
};
xhr.upload.onload = function(e) {
uploading = false;
target.classList.remove("uploading");
target.innerHTML = " ";
};
xhr.send(body);
return false;
}
target.classList.remove("wantdrop");
}
}
});

18.1.5.

HTTP- abort()
XMLHttpRequest. abort() XMLHttpRequest,
XHR2 abort() abort.
(
abort.
onabort XMLHttpRequest.)
abort()
,
. , XMLHttpRequest
.
,
, .
XHR2 timeout,
,
, timeout,
( abort) .

(
XMLHttpRequest timeout ontimeout).

setTimeout() (14.1)
abort(). , 18.12.

18.1. XMLHttpRequest

545

18.12.
// HTTP GET URL.
// responseText
// . ,
// . "readystatechange"
// abort(), status
// , ,
//
// . load.
function timedGetText(url, timeout, callback) {
var request = new XMLHttpRequest(); // .
var timedout = false; // .
// ,
// , .
var timer = setTimeout(function() { // . ,
timedout = true; //
request.abort(); // .
},
timeout); //
request.open("GET", url); // URL
request.onreadystatechange = function() { // .
if (request.readyState !== 4) return; // .
if (timedout) return; // .
clearTimeout(timer); // .
if (request.status === 200) //
callback(request.responseText); // .
};
request.send(null); //
}

18.1.6. HTTP-
(13.6.2), XML
HttpRequest HTTP- ,
.
,
. <form> <iframe>
URL- ,
, . -

.
XMLHttpRequest res
ponseText, XMLHttp
Request . ( ,
<script>
: ,
. 18.2,
<script> Ajax XMLHttpRequest.)
XHR2
-, CORS (Cross-Origin Resource Sharing) HTTP-

546

18. HTTP

. Firefox, Safari
Chrome CORS, IE8
XDomainRequest, . -
:
CORS XMLHttpRequest
-, CORS,

, .
CORS
- ,
, ,
. -, open()
XMLHttpRequest (
).
,
, : cookies
HTTP- ,
cookies, ,
.
, send()
withCredentials XMLHttpRequest true.
withCredentials
CORS , .
18.13 JavaScript-,
XMLHttpRequest HEAD- HTTP
, ,
<a>. HEAD- ,
.
, ,
CORS
.
18.13. HEAD-
CORS
/**
* linkdetails.js
*
* JavaScript <a>
* href title,
* onmouseover. HEAD-
* XMLHttpRequest, ,
* , title ,
* .
*/
whenReady(function() {
// ?
var supportsCORS = (new XMLHttpRequest()).withCredentials !== undefined;
//
var links = document.getElementsByTagName('a');

18.1. XMLHttpRequest

547

for(var i = 0; i < links.length; i++) {


var link = links[i];
if (!link.href) continue; // ,
if (link.title) continue; // title
//
if (link.host!==location.host || link.protocol !== location.protocol)
{
link.title = " "; // ,
//
if (!supportsCORS) continue; // ,
// CORS
// .
// , .
}
// ,
//
if (link.addEventListener)
link.addEventListener("mouseover", mouseoverHandler, false);
else
link.attachEvent("onmouseover", mouseoverHandler);
}
function mouseoverHandler(e) {
var link = e.target || e.srcElement; // <a>
var url = link.href; // URL-
var req = new XMLHttpRequest(); //
req.open("HEAD", url); //
req.onreadystatechange = function() { //
if (req.readyState !== 4) return; // .
if (req.status === 200) { //
var type = req.getResponseHeader("Content-Type"); //
var size = req.getResponseHeader("Content-Length"); //
var date = req.getResponseHeader("Last-Modified"); //
// .
link.title = ": " + type + " \n" +
": " + size + " \n" + ": " + date;
}
else {
//
// " ", .
if (!link.title)
link.title = " : \n" +
req.status + " " + req.statusText;
}
};
req.send(null);
// : .
if (link.removeEventListener)
link.removeEventListener("mouseover", mouseoverHandler, false);
else
link.detachEvent("onmouseover", mouseoverHandler);
}
});

548

18. HTTP

18.2. HTTP-
<script>: JSONP
, <script>
Ajax-: src <script>
( , ),
HTTP-, URL-
. , <script> Ajax-
, ,
.
, <script>
(.. ) , JSON.
<script> Ajax-
JSONP: ,
HTTP- JSON. P
padding, prefix ( ),
.1
, , GET-
JSON.
XMLHttpRequest JSON.
parse(), 18.3.
CORS,
XMLHttpRequest.
, CORS,

<script>. JSON ( )
JavaScript, .
JSON ,
, .
P JSONP.
<script>,
, Java
Script-. , :
[1, 2, {"buckle": "my shoe"}]

, :
handleResponse(
[1, 2, {"buckle": "my shoe"}]
)

<script>,
: JSON (
Java
Script) handleResponse(), , ,
.
1

JSONP (Bob Ippolito) 2005 (http://bob.py


thonmac.org/archives/2005/12/05/remote-json-jsonp/).

18.2. HTTP- <script>: JSONP

549


<script> Ajax-,
- JavaScript,
. , ,
, ,
. ,
, ,
-
, ,
, .
, -
,
, .
<script> Ajax-
- .

,
, <script>
JSON, JSONP. ,
URL, , ?jsonp ( &jsonp).
-, JSONP, ,
handleResponse, .
,
, . 18.14
jsonp.
, JSONP, .
callback,
, ,
.
18.14 getJSONP(),
JSONP. ,
. -, ,
<script>, URL-
. HTTP-. -,

, getJSONP(). ,
:
<script> .
18.14. JSONP
<script>
// URL- JSONP
// . URL
// "jsonp", .
function getJSONP(url, callback) {

550

18. HTTP

//
var cbnum = "cb" + getJSONP.counter++; //
var cbname = "getJSONP." + cbnum; //
// url,
// HTML-. "jsonp". -
// JSONP , "callback".
if (url.indexOf("?") === -1) // URL
url += "?jsonp=" + cbname; //
else //
url += "&jsonp=" + cbname; // .
// script,
var script = document.createElement("script");
// ,
getJSONP[cbnum] = function(response) {
try {
callback(response); //
}
finally { //
delete getJSONP[cbnum]; //
script.parentNode.removeChild(script); // script
}
};
// HTTP-
script.src = url; // url-
document.body.appendChild(script); //
}
getJSONP.counter = 0; // ,

18.3. Comet
Server-Sent Events
Server-Sent Events EventSource,
Comet.
URL- EventSource()
message :
var ticker = new EventSource("stockprices.php");
ticker.onmessage = function(e) {
var type = e.type;
var data = e.data;
// type data.
}

message data, ,
. ,
type, .
message,
. , ,
onmessage,
, type .

18.3. Comet Server-Sent Events

551

, Server-Sent Event,
. ( Event
Source), . ,
.
:
event: bid type
data: GOOG data
data: 999
message

,

,
, .
.
Comet :
XMLHttpRequest
, ,
EventSource. 18.15 ,
EventSource.
18.15. EventSource
<script>
window.onload = function() {
//
var nick = prompt(" "); //
var input = document.getElementById("input"); //
input.focus(); //
// EventSource
var chat = new EventSource("/chat");
chat.onmessage = function(event) { // ,
var msg = event.data; //
var node = document.createTextNode(msg); // .
var div = document.createElement("div"); // <div>
div.appendChild(node); // . div
document.body.insertBefore(div, input); // div input
input.scrollIntoView(); //
} // input
// XMLHttpRequest
input.onchange = function() { // Enter
var msg = nick + ": " + input.value; // + .
var xhr = new XMLHttpRequest(); // XHR
xhr.open("POST", "/chat"); // POST- /chat.
xhr.setRequestHeader("Content-Type", // - UTF-8
"text/plain;charset=UTF-8");
xhr.send(msg); //
input.value = ""; //
} //
};
</script>
<!-- -->

552

18. HTTP

<!-- , , -->
<input id="input" style="width:100%"/>

EventSource Chrome
Safari Mozilla
Firefox, 4.0. ( Firefox),
XMLHttpRequest readystatechange
( 3 readyState) ,
EventSource XMLHttpRe
quest, 18.16. 18.15
Chrome, Safari Firefox. (18.16
IE Opera, XMLHttpRequest
.)
18.16. EventSource XMLHttpRequest
// EventSource , .
// , XMLHttpRequest readystatechange
// HTTP-. ,
// API: readyState, close(),
// open error. , message
// onmessage -- addEventListener
if (window.EventSource === undefined) { // EventSource ,
window.EventSource = function(url) { // .
var xhr; // HTTP-...
var evtsrc = this; // .
var charsReceived = 0; //
var type = null; // type .
var data = ""; //
var eventName = "message"; // type
var lastEventId = ""; //
var retrydelay = 1000; //
var aborted = false; // true,
// XHR
xhr = new XMLHttpRequest();
//
xhr.onreadystatechange = function() {
switch(xhr.readyState) {
case 3: processData(); break; //
case 4: reconnect(); break; //
}
};
//
connect();
// ,
//
function reconnect() {
if (aborted) return; //
//
if (xhr.status >= 300) return; //
setTimeout(connect, retrydelay); //
};

18.3. Comet Server-Sent Events


//
function connect() {
charsReceived = 0;
type = null;
xhr.open("GET", url);
xhr.setRequestHeader("Cache-Control", "no-cache");
if (lastEventId)
xhr.setRequestHeader("Last-Event-ID", lastEventId);
xhr.send();
}
// onmessage.
// Server-Sent Events
function processData() {
if (!type) { // ,
type = xhr.getResponseHeader('Content-Type');
if (type !== "text/event-stream") {
aborted = true;
xhr.abort();
return;
}
}
// ,
// .
var chunk = xhr.responseText.substring(charsReceived);
charsReceived = xhr.responseText.length;
// .
var lines = chunk.replace(/(\r\n|\r|\n)$/,"").split(/\r\n|\r|\n/);
for(var i = 0; i < lines.length; i++) {
var line = lines[i], pos = line.indexOf(":"), name, value="";
if (pos == 0) continue; //
if (pos > 0) { // name:value
name = line.substring(0,pos);
value = line.substring(pos+1);
if (value.charAt(0) == " ") value = value.substring(1);
}
else name = line; // name
switch(name) {
case "event": eventName = value; break;
case "data": data += value + "\n"; break;
case "id": lastEventId = value; break;
case "retry": retrydelay = parseInt(value) || 1000; break;
default: break; //
}
if (line === "") { //
if (evtsrc.onmessage && data !== "") {
//
if (data.charAt(data.length-1) == "\n")
data = data.substring(0, data.length-1);
evtsrc.onmessage({ // Event
type: eventName, //
data: data, //
origin: url //

553

554

18. HTTP

});
}
data = "";
continue;
}
}
}
};
}

Comet .
18.17 HTTP- JavaScript,
Node (12.2).
URL /,
, 18.15, ,
18.16. GET- URL- /chat,
.
POST- /chat,
data:,
Server-Sent Events, .
Node, .
8000,
http://localhost:8000,
.
18.17. , Server-Sent Events
// JavaScript
// NodeJS. , .
// POST- URL /chat,
// /- GET-
// URL. GET- / HTML-,
// .
var http = require('http'); // API HTTP- NodeJS
// HTML- . .
var clientui = require('fs').readFileSync("chatclient.html");
var emulation = require('fs').readFileSync("EventSourceEmulation.js");
// ServerResponse,
var clients = [];
// 20 ,
//
setInterval(function() {
clients.forEach(function(client) {
client.write(":ping\n");
});
}, 20000);
//
var server = new http.Server();
// ,
server.on("request", function (request, response) {
// URL
var url = require('url').parse(request.url);

18.3. Comet Server-Sent Events

555

// URL "/", .
if (url.pathname === "/") { //
response.writeHead(200, {"Content-Type": "text/html"});
response.write("<script>" + emulation + "</script>");
response.write(clientui);
response.end();
return;
}
// URL, "/chat", 404
else if (url.pathname !== "/chat") {
response.writeHead(404);
response.end();
return;
}
// POST- -
if (request.method === "POST") {
request.setEncoding("utf8");
var body = "";
// body
request.on("data", function(chunk) { body += chunk; });
//
// .
request.on("end", function() {
response.writeHead(200); //
response.end();
// /-.
// , "data:"
// .
message = 'data: ' + body.replace('\n', '\ndata: ') + "\r\n\r\n";
//
clients.forEach(function(client) { client.write(message); });
});
}
// ,
else {
// message
response.writeHead(200, {'Content-Type': "text/event-stream" });
response.write("data: Connected\n\n");
// ,
// response
request.connection.on("end", function() {
clients.splice(clients.indexOf(response), 1);
response.end();
});
// response,
clients.push(response);
}
});
// 8000. ,
// http://localhost:8000/
server.listen(8000);

19
19.

jQuery

JavaScript
API,
. IE9 ,
, -
JavaScript,
.

jQuery.1
jQuery , :
, , .
, jQuery ,
. ,
jQuery.
jQuery,
jQuery .
jQuery
: , HTML- CSS-,
.
Ajax,
HTTP-,
.
, jQuery
. CSS-,
, ,
.
1


Prototype, YUI dojo.
, JavaScript libraries.

19.1. jQuery

557

. ,
, ,
,
. ,
jQuery:
(CSS-)

,
, CSS-



(
)
jQuery, ,
.
:
HTML-, CSS,
HTML-,
, , ,

jQuery,

jQuery
HTTP-
Ajax, jQuery
jQuery
jQuery,
jQuery
jQuery,
jQuery UI

19.1. jQuery
jQuery
jQuery(). ,
$, .
, jQuery .1

$
, Prototype, $,
jQuery.noConflict(), $.

558

19. jQuery


jQuery. , ,
<div> :
var divs = $("div");

DOM,
jQuery. , jQuery()
, : ,
new. jQuery
,
, .
, ,
<p>, details:
$("p.details").css("background-color", "yellow").show("fast");

css() jQuery, $(),


, show()
.
jQuery.
, ,
CSS- clicktohide,
. ,
:
$(".clicktohide").click(function() { $(this).slideUp("slow"); });

19.1.1. jQuery()
jQuery() ( $()) jQuery.

.
$()
CSS- ().
, .
CSS3
.
jQuery 19.8.1.
$() jQuery, -
, .
( )
.
$() Element, Document
Window. ,
jQuery .
jQuery DOM.
, , jQuery,
$(document) $(this). jQuery
, , $()
. jQuery
, .

559

19.1. jQuery

jQuery
jQuery
. http://jquery.com.
, -
<script>, :
<script src="jquery-1.4.2.min.js"></script>

min ,
,
,
.
jQuery -
,
URL-:
http://code.jquery.com/jquery-1.4.2.min.js
http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js
http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js

jQuery 1.4.
, 1.4.2 URL-
.1 Google
CDN, 1.4,
1.4.x, 1,
2.0.
,
jQuery -
, -
.

$() HTML.
jQuery HTML- ,
, jQuery.
jQuery ,
jQuery, 19.3, .
, $()
, jQuery , CSS-.
, $(),
HTML- .1
$()
. Document, ,
1

jQuery 1.4.2.
, jQuery 1.5. jQuery1.5
Ajax
19.6.

560

19. jQuery

. (, , ,
<iframe>,
.)
. ,
HTML-,
. ,
css, html, text, width, height, offset, val data,
,
jQuery,
.
(, css(), html() text() 19.2,
19.4). :
var img = $("<img/>", //
{ src:url, //
css: {borderWidth:5}, //
click: handleClick //
});

<img>
HTML-,
CSS-
.

, $() .
,
DOM .
onLoad(), 13.5,
jQuery. jQuery-,
, jQuery():
jQuery(function() { //
// , jQuery
});

$(f), :
$(document).ready(f).

, jQuery(), this,
document, jQuery .
, $ -
, :
jQuery.noConflict(); // $
jQuery(function($) { // $ jQuery
// , jQuery
});

, $(),
jQuery, DOMContentLoaded (13.3.4) ,
, load.
, ,
, .
$() , DOM ,
, $() .
, jQuery jQuery()
.
jQuery.noConflict(),

561

19.1. jQuery

.
jQuery.each(), , jQue
ry.parseJSON() JSON.
19.7,
jQuery
.

jQuery
, ,
:
jQuery
jQuery jQuery $.
jQuery, , ,
DOM ,
jQuery. $().
, jQuery
jQuery,
jQuery.
jQuery
jQuery , jQuery.
jQuery
jQuery, jQuery
.

jQuery CSS-,
jQuery, ,
. jQuery
,
. , attr() :
attr() HTML- .
, : attr()
HTML- jQuery,
. ,
CSS- ,
.
jQuery
jQuery , jQuery.noConflict(),
jQuery.
jQuery .
jQuery
jQuery jQuery,
jQuery. jQuery
, .

562

19. jQuery

jQuery
jQuery,
. ,
:
// each() jQuery, f
// a
$.each(a,f);
// jQuery(), jQuery,
// <a> . each() jQuery,
// f .
$("a").each(f);

jQuery,
http://jquery.com, , $.each,
jQuery, , .each (,
), jQuery.
.
, .

19.1.2.
$() CSS-, jQuery,
() , .
CSS- 15.2.5,
, , , ,
$(). ,
jQuery, 19.8.1.
, ,
, .
$() jQuery. jQuery
, : length
, 0 length-1. ( ,
, 7.11.) ,
jQuery ,
:
$("body").length // => 1: body
$("body")[0] // , document.body

jQuery
, length size(),
get().
jQuery , toArray().
length jQuery ,
. selector (
), jQuery.
context , $()

19.1. jQuery

563

, Document.
, jQuery jquery,
jQuery ,
. jquery
jQuery:
// <script>
var bodyscripts = $("script", document.body);
bodyscripts.selector // => "script"
bodyscripts.context // => document.body
bodyscripts.jquery // => "1.4.2"

jQuery, for
each(). each() forEach()
, ECMAScript 5 (ES5).
,
jQuery ( ).
, .. this
Element. , each()
. ,
this ,
jQuery.
jQuery, $().
each() jQuery ,
forEach(): false
- , (
break ). each()
jQuery, ,
. (
prepend(), 19.3):
// div div#last ()
$("div").each(function(idx) { // <div>
$(this).prepend(idx + ": "); //
if (this.id === "last") return false; //
}); // #last

, each()
, jQuery
.
each() ,
- .
each() ,
jQuery .
jQuery ,
ES5, ,
ES5. map() jQuery ,
Array.map().
jQuery, ,
, jQuery,
. map() , each():

564

19. jQuery

this ,
. null undefined,
jQuery.
,
( jQuery),
jQuery.
, jQuery, map(), ,
, -
, . :
// , id,
// .
$(":header").map(function() { return this.id; }).toArray().sort();

$() querySelectorAll()
$() querySelectorAll() Document,
15.2.5: CSS-
, ,
, . jQuery
querySelectorAll() , ,
,
$(), querySelectorAll():
querySelectorAll()
. $() ,
.
jQuery
, CSS3, $(),
, ,
CSS3.
, , $() ( jQuery),
, (NodeList),
querySelectorAll().

each() map() jQuery


index().
jQuery 1, . ,
jQuery, index() .
index() jQuery,
. , index()
CSS- jQuery,
. index() ,
jQuery .
jQuery,
, is().
true,

19.2. jQuery

565

. ,
each(), :
$("div").each(function() { // <div>
if ($(this).is(":hidden")) return; //
//
});

19.2. jQuery
,
jQuery, HTML-
, CSS, .
, .
,
jQuery:
, jQuery
, .
, . ,
.

, jQuery, jQuery,
.

. (
, map().)
jQuery,
.

.
.

.
. ,
, this,
, .
,
.
/ jQuery.

19.2.1. HTML-
attr() jQuery / HTML-
, , . attr()

HTML-
JavaScript ( ). ,
for htmlFor, class className. removeAttr()

566

19. jQuery

,
. :
$("form").attr("action"); // action 1-
$("#icon").attr("src", "icon.gif"); // src
$("#banner").attr({src:"banner.gif", alt:"Advertisement", // 4
width:720, height:64});
$("a").attr("target", "_blank"); //
$("a").attr("target", function() { //
if (this.host == location.host) return "_self"
else return "_blank"; //
});
$("a").attr({target: function() {...}}); //
$("a").removeAttr("target"); //

19.2.2. CSS-
css() attr(), HTML-,
CSS . css()
( ; 16.4) :
style . ,
, font margin.
, font-weight,
font-family, margin-top margin-left.
css() style . css()
CSS (background-color)
JavaScript (backgroundColor).
css()
.
px (pixels ), :
$("h1").css("font-weight"); // <h1>
$("h1").css("fontWeight"); //
$("h1").css("font"); // :
$("h1").css("font-variant", "smallcaps"); // <h1>
$("div.note").css("border", "solid black 2px"); //
$("h1").css({ backgroundColor: "black", //
textColor: "white", //
fontVariant: "small-caps", //
padding: "10px 2px 4px 20px", //
border: "dotted black 4px" });
// <h1> 25%
$("h1").css("font-size", function(i,curval) {
return Math.round(1.25*parseInt(curval));
});

19.2.3. CSS-
, class ( JavaScript
className) CSS,
. ,
- ,
. jQuery

19.2. jQuery

567

class. addClass() remove


Class() . toggleClass()
, , ,
. hasClass() .
:
// CSS-
$("h1").addClass("hilite"); //
$("h1+p").addClass("hilite first"); //
$("section").addClass(function(n) { //
return "section" + n; //
}); //
// CSS-
$("p").removeClass("hilite"); //
$("p").removeClass("hilite first"); //
$("section").removeClass(function(n) { //
return "section" + n;
});
$("div").removeClass(); //
// CSS-
$("tr:odd").toggleClass("oddrow"); //
//
$("h1").toggleClass("big bold"); //
$("h1").toggleClass(function(n) { //
return "big bold h1-" + n; //
});
$("h1").toggleClass("hilite", true); //
$("h1").toggleClass("hilite", false); //

<h1>
2 <p> <h1>
,


<p>

.

<div>
, ,




addClass
removeClass

// CSS-
$("p").hasClass("first") // - <p> ?
$("#lead").is(".first") //
$("#lead").is(".first.hilite") // is() - , hasClass()

, hasClass() , addClass(),
removeClass() toggleClass(). hasClass()
.
true, ,
false . is() ( 19.1.2)
.
jQuery classList,
16.5, jQuery ,
, classList,
HTML5. , , jQuery
.

19.2.4. HTML-
val() value
HTML-, ,
<select>:

568

19. jQuery

$("#surname").val() // surname
$("#usstate").val() // <select>
$("select#extras").val() // <select multiple>
$("input:radio[name=ship]:checked").val() //
// checked
$("#email").val("Invalid email address") // .
$("input:checkbox").val(["opt1", "opt2"]) //
//
$("input:text").val(function() { //
return this.defaultValue; //
})

19.2.5.
text() html()
HTML.
text()
. ,
textContent innerText (15.5.2).
html() , HTML
. jQuery
innerHTML: x.html() , x[0].innerHTML.
text() html() ,
HTML
. ,
, ,
:
var title = $("head title").text() //
var headline = $("h1").html() //
$("h1").text(function(n,current) { //
return "" + (n+1) + ": " + current //
});


html <h1>

19.2.6.
15.8 ,
, , getBoundingClient
Rect() (15.8.2). jQuery ,
, . ,
, , ,
.
offset() .

left top, X Y.
,
.
CSS- position, :
var elt = $("#sprite"); // ,
var position = elt.offset(); //

19.2. jQuery

569

position.top += 100; // Y
elt.offset(position); //
// <h1> ,
//
$("h1").offset(function(index,curpos) {
return {left: curpos.left + 25*index, top:curpos.top};
});

position() offset(), ,

, . 15.8.5 ,
offsetParent, ,
.
,
, .
jQuery
, offsetParent() jQuery
<body>.
: offset()
, position()
offsetParent().
, ,
, . width() height()
, ,
. innerWidth() innerHeight()
( inner () ,
). outerWidth() outer
Height() .
true, .
,
:
var
var
var
var
var
var
var
var

body = $("body");
contentWidth = body.width();
paddingWidth = body.innerWidth();
borderWidth = body.outerWidth();
marginWidth = body.outerWidth(true);
padding = paddingWidth-contentWidth; //
borders = borderWidth-paddingWidth; //
margins = marginWidth-borderWidth; //

width() height() ,
( inner outer). -,
jQuery Window Document,
.
, .
width() height() ,
. ,
jQuery. (, ,
, Window Document.)
,

570

19. jQuery

. , CSS-
width height,
, CSS. ,
, ,
.
width() height()
.
, , .
CSS-
width height.
. CSS- box-sizing (16.2.3.1),
border-box, width() height()
, . e,
content-box, $(e).width(x).width() x.
, border-box,
.
jQuery,
, scrollTop() scrollLeft(),

. ,
Window, Document
Window, .
, scrollTop() scrollLeft() .
scrollTop()
height(), ,
:
// n . n
function page(n) {
var w = $(window); // jQuery
var pagesize = w.height(); //
var current = w.scrollTop(); //
w.scrollTop(current + n*pagesize); //
} //

19.2.7.
jQuery / data(),
,
Document Window.
:

jQuery,
data() .
jQuery, data()
, . data()
,
/,
jQuery. , ,

19.3.

571

data() , ,
.
, , data() ,
. data() ,
, .
, data() .
, /
, jQuery. data()
,
.
remo
veData(). ( data() null undefined
.) removeData() ,
, .
removeData() , :
$("div").data("x", 1); //
$("div.nodata").removeData("x"); //
var x = $('#mydiv').data("x"); //

, jQuery ,
data() removeData(). ,
e data():
$(e).data(...) //
$.data(e, ...) //

jQuery
,
, .
<applet>, <object> <embed>,
jQuery .

19.3.
19.2.5 html() text(),
. ,
. HTML ,
, ,
, .
jQuery,
.

19.3.1.
. ,
, , ,
.
HTML, , jQuery, Element
Node. , ,

572

19. jQuery

( ) .
,
, .
, .
jQuery, .
, , , replaceWith() ,
jQuery, :
$("#log").append("<br/>"+message); // . #log
$("h1").prepend(""); // <h1>
$("h1").before("<hr/>"); // . <h1>
$("h1").after("<hr/>"); //
$("hr").replaceWith("<br/>"); // <hr/> <br/>
$("h2").each(function() { // <h2> <h1>,
var h2 = $(this); //
h2.replaceWith("<h1>" + h2.html() + "</h1>");
});
// after() before()
// <h1>
$("h1").map(function() { return this.firstChild; }).before("");

, ,
,
. ,
. this
,
jQuery. append(), prepend() replaceWith()
HTML.
before() after() .
, ,
.
, :

. :

$().() $().()

append()

appendTo()

prepend()

prependTo()

after()

insertAfter()

before()

insertBefore()

replaceWith()

replaceAll()

, ,
. , , .
, :

19.3.

573

HTML.
, ,
. ( ,
jQuery, Element Node.)
,
.
jQuery,
. jQuery
, .
,
, jQuery,
. , ,
, jQuery
.
, ,
. ,
$() ( ,
HTML),
.
, :
$("<br/>+message").appendTo("#log"); //
$(document.createTextNode("")).prependTo("h1");
$("<hr/>").insertBefore("h1"); //
$("<hr/>").insertAfter("h1"); //
$("<br/>").replaceAll("hr"); //

html #log
// <h1>
<h1>
<h1>
<hr/> <br/>

19.3.2.
, ,
, ,
. , jQuery
, ,
. ,
, clone().
clone() (
). ,
jQuery, ,
, :
// div id="linklist"
$(document.body).append("<div id='linklist'><h1>List of Links</h1></div>");
// div
$("a").clone().appendTo("#linklist");
// <br/> ,
$("#linklist > a").after("<br/>");

clone() (19.4)
(19.2.7), .
, clone() true.

574

19. jQuery

19.3.3.
HTML-
( ) . jQuery
. wrap() .
wrapInner() .
wrapAll() .

HTML, .
HTML , ,
.
,
(
) , Element jQuery. :
// <h1> <i>
$("h1").wrap(document.createElement("i")); // : <i><h1>...</h1></i>
// <h1>. .
$("h1").wrapInner("<i/>"); // : <h1><i>...</i></h1>
// div
$("body>p:first").wrap("<a name='lead'><div class='first'></div></a>");
// div
$("body>p:not(:first)").wrapAll("<div class='rest'></div>");

19.3.4.
jQuery
. empty() (
) .
remove(), , (
). remove()
, jQuery. ,
,
jQuery, . (
, ,
filter(), 19.8.2.)
,
: ,
.
remove() ( 19.4)
(19.2.7), .
detach() remove(),
. detach() ,
.
, unwrap() ,
, wrap() wrapAll():
,
.
. remove()
detach(), unwrap() .

19.4. jQuery

575

19.4.
jQuery
17, , ,
, IE ( IE9) ,
. ,
jQuery ,
. jQuery
API , IE.
jQuery
, .
.

19.4.1.

jQuery
, .
, click,
click():
// <p>
$("p").click(function() { $(this).css("background-color", "gray"); });

jQuery
. ,

addEventListener() attachEvent().
jQuery
:
blur() focusin() mousedown() mouseup()
change() focusout() mouseenter() resize()
click() keydown() mouseleave() scroll()
dblclick() keypress() mousemove() select()
error() keyup() mouseout() submit()
focus() load() mouseover() unload()


17.
. focus blur ,
focusin focusout, jQuery ,
. mouseover mouseout,
, , ,

. mouseenter mouseleave ,
. IE,
jQuery , .
resize unload Window, ,
, resi

576

19. jQuery

ze() unload() $(window). scroll()


$(window),
, (, ,
CSS- overflow scroll auto). load()
$(window),
load ,
$(), 19.1.1. load()
<iframe> <img>. ,
load()
( HTTP) (
19.6.1). error() <img>
.
onerror Window, 14.6.

, .
hover() mouseenter mouseleave.
hover(f,g)
mouseenter(f) mouseleave(g). hover()
, .

toggle(). click.
, jQuery
, click. , ,
toggle(f,g,h), f()
click, g() , h() f()
click. toggle():
19.5.1,
(.. ) .
19.4.4 ,

.
, $(),
HTML ( ) ,
.
,
attr(). , -
, ,
-
. :
$("<img/>", {
src: image_url,
alt: image_description,
className: "translucent_image",
click: function() { $(this).css("opacity", "50%"); }
});

19.4. jQuery

577

19.4.2. jQuery
,
.
, jQuery
, . ,
, jQuery
.
( ).
Event 17. jQuery
Event ( IE 8 ),
, jQuery
. 19.4.3.

. trigger() (
19.4.6),
.
.
,
, jQuery.
false, ,
, .
false preventDefault() stopPropagation()
Event. , (
undefined), jQuery result
Event, ,
.

19.4.3. Event jQuery


jQuery ,
Event. jQuery ,
Event.
Event jQuery W3C,
, . jQuery Event
Event ( undefined
):
altKey ctrlKey newValue screenX
attrChange currentTarget offsetX screenY
attrName detail offsetY shiftKey
bubbles eventPhase originalTarget srcElement
button fromElement pageX target
cancelable keyCode pageY toElement
charCode layerX prevValue view
clientX layerY relatedNode wheelDelta
clientY metaKey relatedTarget which

Event :

578

19. jQuery

preventDefault() isDefaultPrevented()
stopPropagation() isPropagationStopped()
stopImmediatePropagation() isImmediatePropagationStopped()

17
, Event.
, jQuery ,
, :
metaKey
metaKey, jQuery
ctrlKey. metaKey
MacOS Command.
pageX, pageY
, ,

clientX clientY, jQuery
pageX pageY.
target, currentTarget, relatedTarget
target , .
,
jQuery Element. currentTarget
,
. this.
currentTarget target , ,

target is() (19.1.2):
if ($(event.target).is("a")) return; // ,
//

relatedTarget ,
, mouseover mouseout. , mouse
over relatedTarget ,
target.
relatedTarget, toElement from
Element, relatedTarget
.
timeStamp
, Date.
getTime(). jQuery ,
Firefox.
which
jQuery ,
,
. ,
which, charCode keyCode,
which , .
, which , button,

19.4. jQuery

579

which , button. 0
, . 1 , 2
3 . ( ,
.)
, jQuery
Event, :
data

(19.4.4),
.
handler
.
result
.
, , .
originalEvent
Event, .

19.4.4.

, jQuery
.
, bind(),
jQuery.
bind()
, .1
bind()
.
bind().
$('p').click(f), , :
$('p').bind('click', f);

bind() .
, .
, jQuery
data Event
.
.
1

jQuery
. ECMAScript5 Java
Script bind() ( 8.7.4)
,
. Function.bind() jQuery
jQuery.proxy(), 19.7.

580

19. jQuery

, bind() .
, ,

. $('a').hover(f) (19.4.1), , :
$('a').bind('mouseenter mouseleave', f);

bind()
( )
. ,
,
.
, ,
jQuery. CSS. ,
:
// f, mouseover "myMod"
// <a>
$('a').bind('mouseover.myMod', f);


, :
// f, mouseout "myMod" "yourMod"
$('a').bind('mouseout.myMod.yourMod', f);

bind()
, .
hover(). $('a').hover(f,g)
:
$('a').bind({mouseenter:f, mouseleave:g});

bind()
,
, .
,
.
jQuery . one()
bind(), ,

. , , ,
one(), .
, bind() one(),
,
addEventListener() (17.2.3). IE ( IE9)
, jQuery
.

19.4.5.
bind() (
)

19.4. jQuery

581

unbind(),
. ( , unbind() ,
bind() jQuery.
, addEventListener()
attachEvent(), ,
, onclick onmouseover.) unbind()
( )
jQuery:
$('*').unbind(); // !


( , )
jQuery:
// mouseover mouseout <a>
$('a').unbind("mouseover mouseout");

,
, ,

.
,
unbind()
:
// mouseover mouseout "myMod"
$('a').unbind("mouseover.myMod mouseout.myMod");
// myMod
$('a').unbind(".myMod");
// click "ns1" "ns2"
$('a').unbind("click.ns1.ns2");

,
, ,

unbind() .
( ),
-:
$('#mybutton').unbind('click', myClickHandler);

unbind()
( ) jQuery.
,
unbind() ,
, bind(),
.
unbind() .
unbind()
. ,
:
$('a').unbind({ // mouseover mouseout
mouseover: mouseoverHandler,

582

19. jQuery

mouseout: mouseoutHandler
});

, unbind().
Event, jQuery, ,
. unbind(ev) unbind(ev.
type, ev.handler).

19.4.6.
,

.
. ,
( click() mouseover()) .
jQuery,
, ,
, , . :
$("#my_form").submit(); // ,
//

submit() Event
, submit.
false preventDefault()
Event, . ,
, ,
. ,
.
, jQuery, ,
, jQuery,
, HTML-
Element, onsubmit.
, addEventListener() attach
Event() ( -
).
, jQuery
.
, ,
, , .
click submit,
submit ,
click.
, submit(),
; jQuery bind(),
trigger().
trigger() ,
,
jQuery. submit() :
$("#my_form").trigger("submit");

19.4. jQuery

583

bind() unbind(), trigger()


. , bind()
unbind(), ,
,
. ,
,
. , ,
onclick, , -
:
$("button").trigger("click.ns1"); //
$("button").trigger("click!"); // ,
// -

trigger()
Event ( , type).
type , .
Event jQuery, .
, Event
jQuery , .
:
// onclick button1 button2
$('#button1').click(function(e) { $('#button2').trigger(e); });
//
$('#button1').trigger({type:'click', synthetic:true});
// ,
//
$('#button1').click(function(e) { if (e.synthetic) {...}; });


trigger(). ,
trigger() ,
.
,
:
$('#button1').trigger("click", true); //
$('#button1').trigger("click", [x,y,z]); //

,
, .
$('*') trigger()
, .
, jQue
ry.event.trigger(). , trigger(),
,
. , ,
, ,
, jQuery (
, DOM, ).

584

19. jQuery

trigger() ( ,
) ,
(,
false preventDefault() ). ,
submit <form>, trigger()
submit() , focus, trigger()
focus() .

, trigger() triggerHandler().
, trigger(), ,
preventDefault() cancelBubble() Event.
, ,
, .

19.4.7.
jQuery
, ,
-.
. bind()
, trig
ger() .


/ Observer ().

, jQuery.event.trigger() trigger():
// "logoff",
// ,
// , .
$("#logoff").click(function() {
$.event.trigger("logoff"); //
window.location = "logoff.php"; //
});

19.6.4 , Ajax
jQuery
.

19.4.8.
bind()
, addEventListener() attachEvent() (17). -
, jQuery,
. bind()
<a>, ,
<a>, ,
, .

19.4. jQuery

585

jQuery
. , bind() unbind()
delegate() undelegate().
delegate() $(document),
, ,
(
, jQuery).
, ,
(, ) ,
. ,
mouseover , <a>,
, :
$(document).delegate("a", "mouseover", linkHandler);

bind() ,
delegate() :
//
$("a").bind("mouseover", linkHandler);
// ,
//
$(".dynamic").delegate("a", "mouseover", linkHandler);

, bind() ,
data , delegate()
, .
,
.
, .
, ,
. -
cancelBubble() Event,
.
jQuery live(),
. live()
, delegate(), , bind(),
, .
delegate(), ,
live():
$("a").live("mouseover", linkHandler);
$("a", $(".dynamic")).live("mouseover", linkHandler);

live(), , jQuery,
. ,
( $()),
jQuery. selector
context jQuery (19.1.2). $()
, .
x jQuery
:

586

19. jQuery

x.live(type,handler);
$(x.context).delegate(x.selector, type, handler);

die()
undelegate(). die() .
, ,
,
. ,
. :
$('a').die('mouseover'); //
// mouseover <a>
$('a').die('mouseover', linkHandler); //

undelegate() die(),
(, )
. die()
undelegate(), :
$(document).undelegate('a'); // <a>
$(document).undelegate('a', 'mouseover'); //
// mouseover
$(document).undelegate('a', 'mouseover', linkHandler); //

, undelegate() .
,
.

19.5.
16 , CSS
. , CSS- visibility,
. 16.3.1 , ,
CSS, . ,
, ,
opacity
.
, jQuery .
jQuery
, fadeIn() fadeOut(). animate(),
.
,
animate().
jQuery.
, ,
.
. fast 200
. slow 600. ,
jQuery,
400.
, ,
jQuery.fx.speeds:

19.5.

587

jQuery.fx.speeds["medium-fast"] = 300;
jQuery.fx.speeds["medium-slow"] = 500;

jQuery
. ,
400 .
, ,
, :
$("#message").fadeIn(); // 400
$("#message").fadeOut("fast"); // 200

jQuery .
, fadeIn(),
, .
,
, (
) ,
. , this
, .
:
// , , .
$("#message").fadeIn("fast", function() { $(this).text(", !"); });


. ,
.
jQuery (19.5.2.2
, ).
,
,
, .
, , :
$("#blinker").fadeIn(100).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn();

jQuery
, .
,
:
// ,
$("#message").fadeIn({
duration: "fast",
complete: function() { $(this).text(", !"); }
});


animate(),
.
, ,
.
19.5.2.2.

588

19. jQuery


-,
: ,
- .
,
,
,
.

,
. jQuery
:
jQuery.fx.off true.
0,
, .

, :
$(".stopmoving").click(function() { jQuery.fx.off = true; });

- stop
moving,
.

19.5.1.
jQuery
.
:
fadeIn(), fadeOut(), fadeTo()
: fadeIn() fadeOut()
CSS- opacity, .
,
. fadeTo() :
,
.
fadeTo() (
),
.
.
show(), hide(), toggle()
fadeOut(), , ,
. hide(), ,
, CSS- display
none. hide() show()

19.5.

589

.
, (
), .
hide() 0
0 . show() .
toggle() :
show(), hide().
show() hide(), ,
toggle()
. true toggle() show()
, false hide()
. , toggle()
, ,
19.4.1.
slideDown(), slideUp(), slideToggle()
slideUp() jQuery,
0, CSS- display
none. slideDown() ,
. slideToggle()
, slideUp() slideDown().
,
( ).
.
, jQuery
, :
// , ,
$("img").fadeOut().show(300).slideUp().slideToggle();

jQuery (19.9)
.
jQuery UI (19.10).

19.5.2.

animate()
, . animate()
, .
: ,
CSS- . animate()
CSS-
. ,
slideUp(), , , , :
// 0
$("img").animate({ height: 0 });

animate()
:

590
$("#sprite").animate({
opacity: .25, //
font-size: 10 //
}, {
duration: 500, //
complete: function() { //
this.text(" "); //
}
});

19. jQuery

0,25
10
1/2

.

animate()

. (
), ,
( .)
.
animate() .
CSS-, ,
. ,
jQuery, .

19.5.2.1. ,
animate() .
CSS-,
,
.
:
, -, display.
, ,
. , .
, ,
. ,
: += -=
. :
$("p").animate({
"margin-left": "+=.5in", //
opacity: "-=.1" //
});

, margin-left
.
JavaScript,
. , jQuery
,
marginLeft.
(
+= -=) ,
, . hide
0.
show CSS- .

19.5.

591

show jQuery show()


. hide hide().
toggle,
(show) (hide)
. , , slide
Right ( ,
slideUp(), ):
$("img").animate({
width: "hide",
borderLeft: "hide",
borderRight: "hide",
paddingLeft: "hide",
paddingRight: "hide"
});

show toggle,
, ,
slideDown() slideToggle().

19.5.2.2.
animate()
.
. duration ,
, fast, slow
, jQuery.fx.speeds.
, , complete:
, .
step ,
. , ,
this,
.
queue
.
.
. queue false,
.
. ,
, .
:
$("img").fadeIn(500)
.animate({"width":"+=100"}, {queue:false, duration:1000})
.fadeOut(500);

, fadeIn() fadeOut(),
, , animate() (
width 1000 ) .
fadeIn(). fadeOut()
fadeIn(): , ,
.

592

19. jQuery



. ,
100 ,
400,
25%. opacity 1,0 0,0
(, , fadeOut())
0,75. , ,
, .
jQuery
,
.
jQuery 0
1, 0 1,
jQuery CSS-,
. , ,
0,
0, 1, 1,
,
.
jQuery
: , ,
.
jQuery .
swing, linear.
jQuery.easing:
jQuery.easing["squareroot"] = Math.sqrt;

jQuery UI , the jQuery Easing Plug


in,
.


. easing
. jQuery
swing. ,
, , :
$("img").animate({"width":"+=100"}, {duration: 500, easing:"linear"});

, duration, easing complete


animate() .
:
$("img").animate({"width":"+=100"}, 500, "linear");

19.5.

593

,
jQuery CSS-
. ,
:
// , hide(),
// , // "swing"
// :
// specialEasing,
$("img").animate({ width:"hide", height:"hide", opacity:"hide" },
{ specialEasing: { width: "linear", height: "linear" }});
// :
// [ , ] ,
// .
$("img").animate({
width: ["hide", "linear"], height: ["hide", "linear"], opacity:"hide"
});

19.5.3. ,

jQuery ,
, .
stop():
. stop()
. true,
: ..
,
. false:
, , , .
, CSS-
. true
. false (
) CSS-.
,
,
, . :
// , .
// !
$("img").bind({
mouseover: function() { $(this).stop().fadeTo(300, 1.0); },
mouseout: function() { $(this).stop().fadeTo(300, 0.5); }
});

, , ,
delay(). .
( ),
(

594

19. jQuery

: ). delay()
, :
// , ,
$("img").fadeTo(100, 0.5).delay(200).slideUp();

, stop(),
mouseover mouseout
. ,
. ,
,
:
$("img").bind({
mouseover: function() { $(this).stop(true).delay(100).fadeTo(300, 1.0); },
mouseout: function() { $(this).stop(true).fadeTo(300, 0.5); }
});

, ,
jQuery.
jQuery ,
.
( Document Window),
. queue().
,
. this
, .
. ,
;
. ,
.
,

. ,
:
// , , ,
$("#message").fadeIn().delay(200).queue(function(next) {
$(this).text(", !"); //
next(); //
}).animate({borderWidth: "+=10px;"}); //

, , ,
, jQuery 1.4.

, dequeue():
$(this).dequeue(); // next()

, dequeue() .
, , ,
this , .

19.6. Ajax jQuery

595

, .
clearQueue() .
queue() ,
. queue()
. , jQuery queue()
dequeue() . ,
f e,
:
$(e).queue(f); // jQuery, e, queue
jQuery.queue(e,f); // jQuery.queue()

, , queue(), dequeue() clearQueue()


.
fx
, .
jQuery
:
,
,
. , fx,
, .
, dequeue(),
.

19.6. Ajax jQuery


Ajax -,
HTTP (18)
.
Ajax -,
jQuery ,
. jQuery

. , jQuery.ajax().
,
jQuery.ajax().
jQuery.ajax() , ,
,
.

19.6.1. load()
load() jQuery:
URL-,
,
. :
// 60 .
setInterval(function() { $("#stats").load("status_report.html"); }, 60000);

596

19. jQuery

Ajax,
jQuery
Ajax jQuery,
load(), ,
.
:
success
, .
notmodified
, ,
HTTP- 304 Not Modified, ,
.
, ifModified true (
19.6.3.1.). jQuery 1.4
notmodified ,
.
error
, -
- HTTP-.
, HTTP XMLHttp
Request, .
timeout
Ajax-
, .
Ajax- jQuery
. ,
timeout (19.6.3.1).
parsererror
, HTTP-
, jQuery .
, , XML- JSON-,
. ,
parsererror, parseerror.

load() 19.4.1,
load.
, ,
, Ajax.
,
URL- jQuery. URL-
,
HTML- :

19.6. Ajax jQuery

597

//
$('#temp').load("weather_report.html #temperature");

, URL-
( URL-, ,
14.2). ,
, jQuery
( ) .
URL- load()
. , URL-
. ,
URL ( ? &). ,
/, ,
. (
Ajax 19.6.2.2).
load() HTTP- GET, ,
, POST. :
//
$('#temp').load("us_weather_report.html", "zipcode=02134");
// , ,
//
$('#temp').load("us_weather_report.html", { zipcode:02134, units:'F' });

load() ,
Ajax-, ,
( ) , URL-
.
,
. .
, jQuery,
: ,
URL-, XMLHttpRequest,
.
, jQuery, HTTP,
, success, error timeout.

19.6.2. Ajax
Ajax
jQuery ,
jQuery $, .
jQuery.getScript()
JavaScript. jQuery.getJSON() URL
JSON,
. jQuery.
get(),
URL-. , jQuery.post()
jQuery.get(), HTTP- POST, GET.
load(), :

598

19. jQuery

, - ,
.

19.6.2.1. jQuery.getScript()
jQuery.getScript() URL-
JavaScript.
.
, :
//
jQuery.getScript("http://example.com/js/widget.js");

,
jQuery ,
.
//
jQuery.getScript("js/jquery.my_plugin.js", function() {
$('div').my_plugin(); //
});

, , jQue
ry.getScript() XMLHttpRequest.
( , ,
), jQuery
<script> (18.2).
,
, success XMLHttpRequest,
.
jQuery.getScript() XMLHttpRequest.
, XMLHttp
Request, .
undefined,
jQuery.getScript() undefined.
, jQuery.getScript(),
.
,
jQuery.ajax(). ,
.

19.6.2.2. jQuery.getJSON()
jQuery.getJSON() jQuery.getScript():

. jQuery.getJSON()
,
JSON ( jQuery.parseJSON(): 19.7).
jQuery.getJSON() ,
. URL
, JSON,
.

19.6. Ajax jQuery

599

jQuery.getScript(),
success XMLHttpRequest:
// , data.json : '{"x":1,"y":2}'
jQuery.getJSON("data.json", function(data) {
// data - {x:1, y:2}
});

Ajax
jQuery
Ajax jQuery
( ),
URL. ,
URL, /,
. ( ,
MIME- application/x-www-form-urlencoded.
JSON JavaScript .) HTTP- GET
URL- .
POST
HTTP-.
seria
lize() jQuery, .
, , HTML- load()
:
$("#submit_button").click(function(event) {
$(this.form).load( // , ...
this.form.action, // url
$(this.form).serialize()); // ,
event.preventDefault(); // .
this.disabled = "disabled"; //
}); //

( )
Ajax jQuery , , jQuery
(, )
, jQuery.param().
/
,, {x:1,y:"hello"} "x=1&y=hello".
jQuery 1.4 jQuery.param()
. ,
/
, .
,

. :

600

19. jQuery

$.param({a:[1,2,3]}) // "a[]=1&a[]=2&a[]=3"
$.param({o:{x:1,y:true}}) // "o[x]=1&o[y]=true"
$.param({o:{x:{y:[1,2]}}}) // "o[x][y][]=1&o[x][y][]=2"

jQuery 1.3
jQuery.param() true
traditional true.
,
.
POST- Document
( - ,
). contentType
processData false
jQuery.param().

jQuery.getScript(), jQuery.getJSON()
, , load().
jQuery.getJSON() ,
, .
,
. , URL-,
? &. ,
( ) URL-.
URL , jQuery.getJSON(),
=? ,
JSONP. ( JSONP 18.2.)
jQuery ,
, jQuery.getJSON() ,
, JSON.
JSON- :
, JSONP.
, JSONP ,
.

19.6.2.3. jQuery.get() jQuery.post()


jQuery.get() jQuery.post()
URL, , ,
. jQuery.get() ,
HTTP- GET, jQuery.post() POST,
.
, jQuery.getJSON():
URL-,
, .
,
success XMLHttpRequest (
):

19.6. Ajax jQuery

601

// alert
jQuery.get("debug.txt", alert);

, ,
( ,
),
.
. load() html, jQuery.get
Script() script, jQuery.getJSON() json. jQuery.get()
jQuery.post() , ,
.
jQuery .

,
Ajax jQuery
jQuery.get() jQuery.post()
. , ,
jQuery.ajax() dataType:
"text"
, .
"html"
, "text":
. load(),
.
"xml"
, URL- XML,
responseText XMLHttpRequest
jQuery responseXML.
, Document,
XML-.
"script"
, URL-
JavaScript,
. jQuery.get
Script(). "script",
<script>
XMLHttpRequest.
"json"
, URL-
JSON. ,

jQuery.parseJSON() ( 19.7).
jQuery.getJSON(). "json" URL
"=?", "jsonp".

602

19. jQuery

"jsonp"
, URL- ,
JSONP JSON
. (
JSONP 18.2.) ,
.
JSONP- <script>,
,
"script". URL
"&jsonp=?" "&callback=?".
jQuery
. (
jsonp jsonpCallback, 19.6.3.3,
.)
jQuery.get(), jQuery.post() jQuery.ajax()
, jQuery Content-Type
HTTP-. xml,
XML-. ,
json, , JSON,
. ,
JavaScript,
. .

19.6.3. jQuery.ajax()
Ajax jQuery
jQuery.ajax() .
jQuery.ajax() : ,
, Ajax-. jQuery.
getScript(url,callback), ,
jQuery.ajax():
jQuery.ajax({
type: "GET", //
url: url, //
data: null, //
dataType: "script", //
success: callback //
});

HTTP-.
URL- .
URL.
.
.


jQuery.get() jQuery.post().
jQuery.ajax()
. ( , )
.

19.6. Ajax jQuery

603

, ,
,
jQuery.ajaxSetup():
jQuery.ajaxSetup({
timeout: 2000, // Ajax- 2
cache: false // , URL
});

, ,
timeout cache Ajax- (
, jQuery.get() load()),
.


, Ajax-
19.6.1 19.6.2.3.

Ajax jQuery 1.5


jQuery 1.5, , ,
Ajax ,
. ,
jQuery.ajax() Ajax, ,
jqXHR.
XMLHttpRequest (,
$.getScript()), XMLHttpRequest. ,
jqXHR success() error(),
,
.
jQuery.get(), ,
success() jqXHR,
:
jQuery.get("data.txt")
.success(function(data) { console.log(" ", data); })
.success(function(data) { process(data); });

19.6.3.1.
,
jQuery.ajax():
type
HTTP-. GET.
POST.
HTTP-, DELETE PUT,
. ,

604

19. jQuery

:
,
method.
url
URL- . GET-
data URL-. jQuery
URL JSONP-
cache false.
data
, URL- ( GET-)
( POST-). .
,
19.6.2.2, ,
processData.
dataType

jQuery. text, html, script, json,
jsonp xml. 19.6.2.3.
. ,
jQuery Content-Type , ,
.
contentType
HTTP- Content-Type .
application/x-www-form-urlencoded,
HTML- .
type POST
XML-, .
timeout
.
,
error
timeout. timeout 0,
,
.
cache
GET-,
false, jQuery _= URL
.
( ).
, ,
, URL .
ifModified
true, jQuery
Last-Modified If-None-Match
URL-

19.6. Ajax jQuery

605

URL-.
HTTP- 304 Not Modified,
URL- .
jQuery
.
jQuery HTTP- 304 notmodified.
notmodified
success success.
ifModified,
notmo
dified, ( )
undefined. , jQuery 1.4 HTTP- 304
, notmodified
error, success.
19.6.1.
global
, jQuery
Ajax-. true.
false, ,
Ajax. (
19.6.4.) :
global, jQuery
, .

19.6.3.2.
,
Ajax-. success :
, , jQuery.getJSON().
, jQuery
Ajax- ( global
false).
context
,
this .
, ,
,
. context
Ajax ( 19.6.4).
Window, Document Element,
.
beforeSend
,
Ajax- .
XMLHttpRequest, .
beforeSend HTTP-
XMLHttpRequest. false,
Ajax- . ,

606

19. jQuery

script jsonp XMLHttpRequest


, beforeSend, .
success
,
Ajax-.
, . ,
jQuery, XMLHttpRequest,
. 19.6.2.3,
dataType
Content-Type . xml,
Document. json
jsonp, ,
JSON. script,
(
,
). ,
.
success. ,
ifModified,
notmodified.
, undefined.
script jsonp
<script>, XMLHttpRequest,
XMLHttpRequest
undefined.
error
,
Ajax-.
XMLHttpRequest ( ).
, jQuery.
error HTTP, timeout
parsererror ,
. , XML- JSON
, parser
error. error
Error, . ,
dataType="script", Ja
vaScript, .
error success.
complete
,
Ajax-. Ajax-
success, error. jQuery
complete success error.
complete XMLHttpRequest,
.

19.6. Ajax jQuery

607

19.6.3.3.
.
, ,
, Ajax, jQuery .
async
HTTP .
XMLHttpRequest
. false,
jQuery .
, jQuery.ajax():
XMLHttpRequest, .
HTTP
XMLHttpRequest complete
( ),
jQuery.
dataFilter

, .
, ( ,
Document, XML-),
dataType. ,
. ,
dataFilter JSON
. , , dataFilter
script jsonp.
jsonp
dataType jsonp, url
data jsonp=?.
jQuery URL- ,
, jsonp
. jsonp callback.
, ,
JSONP,
URL .
JSONP 18.2.
jsonpCallback
dataType, jsonp ( json,
URL- , jsonp=?),
jQuery URL,
-, .
jQuery ,
. ,
. ,
jQuery success complete
.

608

19. jQuery

processData
data (
jQuery.get() ),
jQuery application/xwww-form-urlencoded ( 19.6.2.2).
(,
Document POST-), false.
scriptCharset
script jsonp,
<script>,
charset . ,
XMLHttpRequest.
traditional
jQuery 1.4
application/x-www-form-urlencoded
( 19.6.2.2).
true, , jQuery
.
username, password

, .
xhr
, XMLHttp
Request. ,
XMLHttpRequest.

XMLHttpRequest
.

19.6.4. Ajax
19.6.3.2 , jQuery.ajax()
, : beforeSend, success, error complete.
, Ajax
jQuery
. ,
, :

beforeSend

ajaxSend

ajaxSend()

success

ajaxSuccess

ajaxSuccess()

error

ajaxError

ajaxError()

complete

ajaxComplete

ajaxComplete()

ajaxStart

ajaxStart()

ajaxStop

ajaxStop()

19.6. Ajax jQuery

609

bind()
(19.4.4), ,
. ajaxSuccess()
, click(), mouseover() ,
19.4.1.
, Ajax,
jQuery, ,
Event, , -
. ajaxSend, ajaxSuccess, ajaxEr
ror ajaxComplete .
.
XMLHttpRequest,
. , ,
ajaxSend, XMLHttpRequest,
beforeSend. ajaxError
,
. Error,
, .
, Ajax ,
jQuery. , , ajax
Success success notmodified,
HTTP- XMLHttpRequest.
, ,
, , ,
. ajaxStart
ajaxStop ,
Ajax-. jQuery
Ajax- ,
ajaxStart. , ,
,
ajaxStart. ajaxStop ,
Ajax- jQuery
.
... ,
. :
$("#loading_animation").bind({
ajaxStart: function() { $(this).show(); },
ajaxStop: function() { $(this).hide(); }
});

ajaxStart ajaxStop
: jQuery ( 19.4.6),
- . Ajax
ajaxSend, ajaxSuccess, ajaxError ajaxComplete
,
. context
jQuery.ajax(),
.

610

19. jQuery

, , Ajax
jQuery , global false.
global,
false ,
context.

19.7.
jQuery (
), .
,
ECMAScript5 (ES5). jQuery
ES5 .
:
jQuery.browser
browser , ,
(13.4.5).
IE, msie true. Firefox
true mozilla. Safari
Chrome true webkit, Opera
true opera. browser
version, .
, ,
,
, :
if ($.browser.mozilla && parseInt($.browser.version) < 4) {
// Firefox...
}

jQuery.contains()
.
true, , false.
jQuery.each()
each(),
jQuery, jQuery.each()
.
, .
,
.
:
. this
. false, jQuery.each()
, . jQuery.each()
.
jQuery.each() ,
for/in, ..
, .

19.7.

611

jQuery.each() ,
.
jQuery.extend()
.
,
. ,
undefined null. ,
jQuery.
, .
true, ,
, :
( ) .

:
var clone = jQuery.extend({}, original);
var options = jQuery.extend({}, default_options, user_options);

jQuery.globalEval()
JavaScript
, <script>.
( <script>
.)
jQuery.grep()
filter() Array,
ES5. , -
,
. jQuery.grep() ,
-, -
true ( ,
). jQuery.grep() true,
-
, - .
jQuery.inArray()
indexOf() Array,
ES5. ,
( , )
, , 1,
.
jQuery.isArray()
true, Array.
jQuery.isEmptyObject()
true, .
jQuery.isFunction()
true, Function.
, IE 8 , ,
Window.alert() Element.attachEvent(), .

612

19. jQuery

jQuery.isPlainObject()
true, ,
.
jQuery.makeArray()
, ,
() .
, ,
.
jQuery.map()
map() Array,
ES5. ,
, .
,
, . jQuery.map()
map() ES5. null,
.
,
, .
jQuery.merge()
, ,
.
, . ,
, :
var clone = jQuery.merge([], original);

jQuery.parseJSON()
JSON .
, .
jQuery JSON.parse(),
. , jQuery
JSON,
JSON.
jQuery.proxy()
bind() (8.7.4) Function,
ES5. ,
,
.
, bind().
jQuery.proxy()
.
. jQuery.proxy(o,n)
, jQuery.proxy(o[n],o).
jQuery.proxy()
jQuery.
, jQuery.proxy(),
, .

19.8. jQuery

613

jQuery.support
jQuery.browser,
(13.4.3)
. jQuery.
support ,

. jQuery.support
,
jQuery.
.
jQuery.support.boxModel: true,
context-box, CSS,
false IE6 IE7, (16.2.3.1).
jQuery.trim()
trim(), ES5.
,
.

19.8.
jQuery
$()
jQuery, CSS-.
jQuery, ,
.

19.8.1. jQuery
jQuery ,
CSS3 Selectors,
, . CSS-
15.2.5.
. ,
, jQuery.
CSS, .
.
. #test
id, test. blockquote
<blockquote> , div.note
<div> class, note.
, div.note>p block
quote i, -. ,
, .
,
$().
,
.

614

19. jQuery

19.8.1.1.
( ) . , ,
<p>,
p. ,
*.
, .

, . ,
, .
, ,
. , jQuery, . .19.1.
, , .19.1,
. , ,
,
, JavaScript
<a>.
p:nth-child(3n+1):text(JavaScript):not(:has(a))

, .
, :radio
input:radio.
, id, ,
. , #address
, form#address.
19.1. , jQuery

#id

id, id.
HTML-
id,
.

.class

class, (
, ) class.

[attr]

, attr ( ).

[attr=val]

, attr val.

[attr!=val]

, attr,
attr, val ( jQuery).

[attr^=val]

attr,
val.

[attr$=val]

attr,
val.

[attr*=val]

attr, val.

[attr~=val]

attr, , , , val.
div.note , div[class~=note].

19.8. jQuery

615

[attr|=val]

attr,
val , ,
.

:animated

,
jQuery.

:button

<button type="button"> <input type="button">


( jQuery).

:checkbox

<input type="checkbox"> ( jQuery).


input: in
put:checkbox.

:checked

:contains(text) , text (
jQuery). , ..
.
textContent innerText; ,
,
.
:disabled

:empty

, ,
.

:enabled

:eq(n)

n- ,
,
( jQuery).

:even

.
0,
, , ( ) ( jQuery).

:file

<input type="file"> ( jQuery).

:first

. , :eq(0) (
jQuery).

:first-child

,
. ,
:first.

:gt(n)

,
, ,
n ( jQuery).

:has(sel)

, ,
sel.

:header

-: <h1>, <h2>, <h3>, <h4>, <h5>


<h6> ( jQuery).

:hidden

, .. ,
offsetWidth offsetHeight 0.

:image

<input type="image">. ,
<img> ( jQuery).

:input

: <input>, <textarea>, <select> <button> (


jQuery).

616

19. jQuery
19.1 ()

:last

( jQue
ry).

:last-child

,
. ,
:last.

:lt(n)

,
, ,
n ( jQuery).

:not(sel)

, sel.

:nth(n)

:eq(n) ( jQuery).

:nth-child(n)

, n-
. n , even, odd
. , ( )
:nthchild(even). , ( )
:nth-child(odd).
n xn xn+y, x y
, n n. nth-child(3n+1)
, , ( ) .
,
,
3n+1, 3n.
:even :odd,
.

:odd

(
). , 1 3
, ( jQuery).

:only-child

,
.

:parent

, .
:empty ( jQuery).

:password

<input type="password"> ( jQuery).

:radio

<input type="radio"> ( jQuery).

:reset

<input type="reset"> <button type="reset"> (


jQuery).

:selected

<option>, .
()
:checked ( jQuery).

:submit

<input type="submit"> <button type="submit">


( jQuery).

:text

<input type="text"> ( jQuery).

:visible

, , ..
, offsetWidth offsetHeight .
:hidden.

19.8. jQuery

617

19.8.1.2.

, ,
. .19.2 ,
jQuery.
CSS3.
:
"blockquote i" //
"ol > li" //
"#output + *" //
"div.note > h1 + p" //

<i> <blockquote>
<li>, <ol>
, id="output"
<p>, <h1> <div class="note">

,
:
. .
19.2. , jQuery


A B

, B
, A.
, - .

A > B

, B
,
A.

A + B

, B
,
A ( ).

A ~ B

, B
, A.

19.8.1.3.
, ,
$() ( ),
, .
,
.
.
:
"h1, h2, h3" //
"#p1, #p2, #p3" //
"div.note, p.note" //
"body>p,div.note>p" //

<h1>, <h2> <h3>


id, p1, p2 p3
<div> <p> class="note"
<p>, <body>, <div class="note">

, CSS jQuery
,
.

618

19. jQuery


, :
(h1, h2, h3)+p //
h1+p, h2+p, h3+p //

19.8.2.
, $(),
jQuery .
jQuery, ,
.
: , ,
.
. ,
,
.

. first() jQuery,
, last() jQuery,
. eq()
jQuery,
. ( jQuery 1.4
, .)
, jQuery
, ,
jQuery, :
var paras = $("p");
paras.first() //
paras.last() //
paras.eq(1) //
paras.eq(-2) //
paras[1] //

<p>
<p>
<p>
<p>
<p>

slice().
Array.slice():
( )
jQuery,
, . ,
:
$("p").slice(2,5) // 3-, 4- 5- <p>
$("div").slice(-3) // <div>

filter()
:
filter() , jQuery,
,
.
filter() jQuery,
jQuery,

19.8. jQuery

619

jQuery.
.
filter() -,
filter() jQuery,
, - true (
).
this, . (
jQuery.grep() 19.7.)
$("div").filter(".note") // $("div.note")
$("div").filter($(".note")) // $("div.note")
$("div").filter(function(idx) { return idx%2==0 }) // $("div:even")

not() , filter(), ,
. not()
, jQuery,
, . not()
jQuery, ,
, , . not() , , filter(),
jQuery, ,
false :
$("div").not("#header, #footer"); // <div>,

jQuery 1.4 has(),


. , jQuery,
, ,
. has() ,
, :
$("p").has("a[href]") // ,

add() , . add()
( ),
$(). ,
, ( )
$(). add()
:
// <div> <p>
$("div, p") //
$("div").add("p") // add()
$("div").add($("p")) // add() jQuery
var paras = document.getElementsByTagName("p"); // ,
$("div").add(paras); // add()

19.8.2.1.

filter(), add() not(), , ,
.
jQuery ,

620

19. jQuery

.
,
, ,
jQuery, . add(),

.
find().
,
, jQuery,
. ,

. , find()
filter(),
, :
$("div").find("p") // <p> <div>. , $("div p")

jQuery,
,
.
. , ,
, .
, .
children() ,
:
// <span>,
// id="header" id="footer".
// $("#header>span,#footer>span")
$("#header, #footer").children("span")

contents() , children(),
, , . ,
<iframe> contents() Document
. , contents()
,
Document, ,
.
next() prev()
, .
, , :
$("h1").next("p") // , $("h1+p")
$("h1").prev() // <h1>

nextAll() prevAll()
( ) . siblings()
(
).
, ,
:

19.8. jQuery

621

$("#footer").nextAll("p") // <p>, #footer


$("#footer").prevAll() // , #footer

jQuery 1.4 nextUntil() prevUntil()


,
, ,
. ,
nextAll() prevAll() .
parent() :
$("li").parent() // , <ul> <ol>

parents() ( <html>)
. , parent() parents(),
:
$("a[href]").parents("p") // <p>,

parentsUntil() ,
, .
closest()
( ) ,
.
. jQuery 1.4 closest()
, jQuery
:
$("a[href]").closest("div") // <div>,
$("a[href]").parentsUntil(":not(div)") // <div>,
// <a>

19.8.2.2.
,
jQuery ,
. , ,
jQuery. ,
, , ,
, ,
.
. ,
, jQuery,
jQuery,
. , jQuery. end()
jQuery.
end()
. :
// <div>,
// <p>. <p> <div>.
// ,
var divs = $("div");
var paras = divs.find("p");

622

19. jQuery

paras.addClass("highlight");
divs.css("border", "solid black 1px");
// ,
$("div").find("p").addClass("highlight").end().css("border", "solid black 1px");
// end(),
$("div").css("border", "solid black 1px").find("p").addClass("highlight");

-
end(),
, ,
pushStack().
, ,
end():
var sel = $("div"); // <div>
sel.pushStack(document.getElementsByTagName("p")); //
// <p>
sel.end(); // <div>

, end() ,
, .
andSelf() jQuery,
(
) . andSelf()
add() addPrev.
:
<p> <div>
<div>:
$("div").find("p").andSelf(). //
addClass("highlight"). //
end().end(). //
css("border", "solid black 1px"); //

<p> <div>

$("div")
<div>

19.9. jQuery

jQuery ,
. ,
, (plug-in),
http://plugins.jquery.com. jQuery
JavaScript, ,
-,
<script>, JavaScript
(,
jQuery).
jQuery
. - jQuery.fn,
jQuery.
, jQuery. :

19.9. jQuery

623

jQuery.fn.println = function() {
// ,
var msg = Array.prototype.join.call(arguments, " ");
// jQuery
this.each(function() {
// <br/>.
jQuery(this).append(document.createTextNode(msg)).append("<br/>");
});
// jQuery,
return this;
};

jQuery.fn.println,
println() jQuery, :
$("#debug").println("x = ", x, "; y = ", y);

jQuery.fn . ,
jQuery
each() ,
,
each() .
,
jQuery,
. ,
jQuery:
$:
jQuery.noConflict(), $()
jQuery(). , ,
jQuery $. ,
,
.
jQuery
$:
(function($) { // $
//
}(jQuery)); // jQuery

- ,

jQuery,
. this,
.
return this;.
( ),
: each(). , println()
return this.each(function() {...});

,
( animate() 19.5.2
jQuery.ajax() 19.6.3).

624

19. jQuery

jQuery .

jQuery
, .
jQuery jQuery.fn
.
, .
,
. ,
.
,
(19.4.4).
.
data()
,
, , .
jquery.
plugin.js, plugin .
,
jQuery. :
// ( println())
// id="debug". ,
// .
jQuery.debug = function() {
var elt = jQuery("#debug"); // #debug
if (elt.length == 0) { // ,
elt = jQuery("<div id='debug'><h1>Debugging Output</h1></div>");
jQuery(document.body).append(elt);
}
elt.println.apply(elt, arguments); //
};


jQuery. 19.5, , ,
,
( fast slow), jQuery.fx.speeds,
, jQuery.easing.
,
jQuery! ,
( :first :input), jQuery.
expr[':']. :draggable,
draggable=true:
jQuery.expr[':'].draggable = function(e) { return e.draggable === true; };

,
$("img:draggable") $("img[draggable=true]").
,
DOM . true,
, false .
,

19.10. jQuery UI

625

. ,
.
, .
:
.exec() RegExp. ( 3)
, (
). ,
. , ,
:data(x), true ,
data-x (15.4.3):
jQuery.expr[':'].data = function(element, index, match, array) {
// : IE 7 hasAttribute()
return element.hasAttribute("data-" + match[3]);
};

19.10. jQuery UI
, jQuery,
DOM, CSS,
Ajax.
,
, jQuery UI.
jQuery UI
, , , .
http://jqueryui.com.
, jQuery UI
: ,
,
,

. jQuery UI
,
, ,
. , jQuery UI
( )
, jQuery,
.
jQuery UI
jQuery, . jQuery UI,
-
jQuery. Download (), http://jqueryui.com,
, ,
,

jQuery UI.
jQuery UI ,
CSS.

626

19. jQuery

jQuery UI CSS
. jQuery UI
, ThemeRoller,
.
jQuery UI
, jQuery.
,
, . ,
,
, datepicker(), :
// <input> class="date"
$("input.date").datepicker();

jQuery UI
: , .
jQuery UI ,
.
, (
, animate()) .
jQuery UI
. ,
jQuery, jQuery UI
. (
datepicker() ).
,
, . ,
, disableDatepicker();
datepicker("disable").
, jQuery UI ,
.
bind()
,
. , ,
Event.
. , ,
.
, jQuery UI
,
,
. ,
,
. ,
,
bind().

datepicker().

20
20.

-
, .
. - , ,
,
,
.
,
, .

. , , ,
. -
: , ..
,
, ,
.
:
Web Storage
Web Storage ,
HTML5,
.
, ( )
, IE8.
localStorage sessionStorage, , ,
,
. Web Storage ,
( )
, . localSto
rage sessionStorage 20.1.

628

20.

Cookies
Cookies ,
. Java
Script ,
cookies ,
.
, , cookies,
HTTP-,
. cookies -
,
, .
Web Storage , cookies

. cookies
20.2.
IE User Data
Microsoft IE 5
, userData.
userData
Web Storage
IE 7 . userData
20.3.
Offline Web Applications
HTML5 Offline
Web Applications ( -),
- (, CSS-,
..). -
, , -
,
. - 20.4.

, -
, ,

. Safari, Chrome Opera
SQL.
,
, Firefox IE.
,
Indexed Database API.
, .

, .
, 22.8 IndexedDB API.

629


18 ,
File, XMLHttpRequest ,
.
,
,
.
22.7. , -
,
, .

,
-
.
, ,
: , ,
.
,
, (
, ),
.
,
.
: , -
-, ,
.
. ,
.


.
, , -,
cookies
, .
, ,
,
.
, ,
,
, ,
.

630

20.

20.1. localStorage sessionStorage


, Web Storage,
Window : localStorage sessionStorage.
Storage ,
. Storage
JavaScript:
, . local
Storage sessionStorage :
, .
.
. local
Storage, sessionStorage:
var name = localStorage.username; //
name = localStorage["username"]; //
if (!name) {
name = prompt(" ?"); //
localStorage.username = name; //
}

.
,
.
.

// /
for(var name in localStorage) { //
var value = localStorage[name]; //
}

Storage ,
. 20.1.2.
Web Storage
( ),
, ,
File.
. ,
. :
// .
// .
localStorage.x = 10;
var x = parseInt(localStorage.x);
// Date
localStorage.lastRead = (new Date()).toUTCString();
var lastRead = new Date(Date.parse(localStorage.lastRead));
//
// JSON
localStorage.data = JSON.stringify(data); //
var data = JSON.parse(localStorage.data); // .

20.1.1.
localStorage sessionStorage
. localStorage

20.1. localStorage sessionStorage

631

: ,
, -
(
, ) .
localStorage
. 13.6.2,
, , ,
URL- :
http://www.example.com //
https://www.example.com //
http://static.example.com //
http://www.example.com:8000 //

: http; : www.example.com


, ,
localStorage (
, localStorage).
.
(
,
).
, localStorage
. Firefox,
, , Chrome, ,
, .
, sessionStorage, :
, ,
, .
, sessionStorage, . (, ,

,

sessionStorage , .)
sessionStorage, localStorage,
, ..
session
Storage. sessionStorage
. ,
,
sessionStorage. ,
, , ,

. ,
sessionStorage .
<iframe>
,
sessionStorage.

632

20.

20.1.2.
Storage
localStorage sessionStorage
JavaScript:
, .
, .
setItem(), .
getItem(), .
removeItem(), . (
delete,
, IE8.)
clear() ( ). ,
length
key(), 0 length-1.
localStorage.
sessionStorage:
localStorage.setItem("x", 1); // "x"
localStorage.getItem("x"); //
// -
for(var i = 0; i < localStorage.length; i++) { // length
var name = localStorage.key(i); // i-
var value = localStorage.getItem(name); //
}
localStorage.removeItem("x"); // "x"
localStorage.clear(); //

,
, .
-, clear()
/ Storage. removeItem()
/
, IE8 delete .

Storage ,
, setItem() getItem().
, Storage
,
. Storage
,
.
,
. (,
) :
localStorage.o = {x:1}; // , x
localStorage.o.x = 2; //
localStorage.o.x // => 1: x

20.1. localStorage sessionStorage

633


,
,
.
. , getItem():
localStorage.getItem("o").x = 2; // 2

,

,
Web Storage.
Storage
cookies userData IE.
,
localStorage, ,
.
:
// ,
var memory = window.localStorage ||
(window.UserDataStorage && new UserDataStorage()) ||
new CookieStorage();
//
var username = memory.getItem("username");

20.1.3. Storage
, localStorage sessionStorage,
storage Window,
( , ).

localStorage,
storage. , ,
sessionStorage, ,
sessionStorage storage
. , storage
, .
,
, .
storage
addEventListener() ( attachEvent() IE).
onstorage Window,
Firefox.
, storage,
(, IE8):
key
.
clear(), null.

634

20.

newValue
null, removeItem().
oldValue
, ,
null, .
storageArea
localStorage sessionStorage
Window.
url
URL- ( ) ,
.
, , localStorage storage
,
,
-. , -
,
localStorage,
.
, , ,
. -
,
.
localStorage
,
.

20.2. Cookies
Cookies , -
- -. Cookies

HTTP. cookies
- -,
,
. ,
cookies, cookie Document.
cookies ,
, . ,
. :
, cookies cookie
Document .
cookie
.
cookie.

635

20.2. Cookies

cookie?
cookie () ,
. cookie,
magic cookie,
, , ,
, . JavaScript
cookies
-,
(,
https:).

,
cookies,
, cookies JavaScript.
cookies
, Storage.

, cookies
Cookies
- cookies,
-, . , cookies
, ,
,

cookies -. ,
cookies JavaScript, ,
. ,
navigator.cookieEnabled. true,
, cookies , false (
cookies,
).
navigator.cookieEnabled ,
, , ,
cookies, ,
cookie, , .

20.2.1. cookie:

cookie ,
. cookies

636

20.

-
. ,
sessionStorage: cookies
,
, - .
cookie ,
, () , maxage. , cookie
.
cookie ,
localStorage sessionStorage,
. cookie path
domain. cookie -
,
. , , - http://www.example.com/catalog/
index.html cookie, cookie http://
www.example.com/catalog/order.html http://www.example.com/catalog/widgets/in
dex.html, http://www.example.com/about.html.
, , .
cookie
- , cookie. ,
,
.

,
, , .
cookie path.
- URL-, ,
cookie. , cookie,
http://www.example.com/catalog/widgets/index.html, path
/catalog, cookie http://www.
example.com/catalog/order.html. path /,
cookie - http://www.example.com.
path /
cookie, localStorage, ,
cookie -
. , path
. -
cookies, - -
, <iframe>
cookies, .
( 13.6.2) cookies,
- ,
.
cookies .
-
cookies . , order.examp
le.com cookie,

20.2. Cookies

637

catalog.example.com. domain. cookie,


catalog.example.com, path
/, domain .example.com, cookie
- catalog.example.com, orders.example.com
example.com. domain
, -,
. , domain ,
.
cookie secure,
, cookie . cookie ,
.. HTTP-.
cookie , ,
HTTPS
.

20.2.2. cookies
cookie ,
cookie :
=

:
document.cookie = "version=" + encodeURIComponent(document.lastModified);

cookie /
cookies . cookie
, .
cookie, ,
JavaScript- encodeURIComponent().
cookie decodeURIComponent().
cookie -
, . cookie,
,
() max-age. ,
cookie :
=; max-age=_

cookie max-age:
// / cookie,
// encodeURIComponent(), , .
// daysToLive , max-age
// , cookie
// . 0, cookie .
function setCookie(name, value, daysToLive) {
var cookie = name + "=" + encodeURIComponent(value);
if (typeof daysToLive === "number")
cookie += "; max-age=" + (daysToLive*60*60*24);
document.cookie = cookie;
}

638

20.

path, domain secure,


cookie
cookie:
; path=
; domain=
; secure

cookie, ,
, , . cookie
, max-age.
cookie, , , ,
( ) , max-age 0.

20.2.3. cookies
cookie JavaScript-,
cookies, .
= ,
. - ,
cookie. document.cookie
split(),
/.
cookie cookie
, ,
cookie. , cookie decodeURIComponent(),
JSON.parse().
20.1 getCookie(),
document.cookie ,
/ cookies .
20.1. document.cookie
// cookies /.
// , cookie
// encodeURIComponent().
function getCookies() {
var cookies = {}; //
var all = document.cookie; // cookies
if (all === "") // ,
return cookies; //
var list = all.split("; "); // /
for(var i = 0; i < list.length; i++) { // cookie
var cookie = list[i];
var p = cookie.indexOf("="); // =
var name = cookie.substring(0,p); // cookie
var value = cookie.substring(p+1); // cookie
value = decodeURIComponent(value); //
cookies[name] = value; //
}
return cookies;
}

20.2. Cookies

639

20.2.4. cookies
Cookies
,
URL-. , cookies,

cookies, 300 cookies, 20 cookies
- 4 cookie (
cookie, ).
300 cookies, 4
cookie - .

20.2.5. cookies
20.2 , cookies ,
Storage. Co
okieStorage() max-age path
, localStorage session
Storage. , storage

CookieStorage.
20.2. Storage cookies
/*
* CookieStorage.js
* Storage,
* localStorage sessionStorage, HTTP Cookies.
*/
function CookieStorage(maxage, path) { //
//
// , cookies
var cookies = (function() { // getCookies(),
var cookies = {}; //
var all = document.cookie; // cookies
if (all === "") //
return cookies; //
var list = all.split("; "); // /
for(var i = 0; i < list.length; i++) { // cookie
var cookie = list[i];
var p = cookie.indexOf("="); // =
var name = cookie.substring(0,p); // cookie
var value = cookie.substring(p+1); // cookie
value = decodeURIComponent(value); //
cookies[name] = value; //
}
return cookies;
}());
// cookies
var keys = [];
for(var key in cookies) keys.push(key);

640

20.

// Storage API
// cookies
this.length = keys.length;
// n- cookie null, n
this.key = function(n) {
if (n < 0 || n >= keys.length) return null;
return keys[n];
};
// cookie null.
this.getItem = function(name) { return cookies[name] || null; };
//
this.setItem = function(key, value) {
if (!(key in cookies)) { // cookie
keys.push(key); //
this.length++; // length
}
// / cookies.
cookies[key] = value;
// cookie.
//
// =-
var cookie = key + "=" + encodeURIComponent(value);
// cookie
if (maxage) cookie += "; max-age=" + maxage;
if (path) cookie += "; path=" + path;
// cookie document.cookie
document.cookie = cookie;
};
// cookie
this.removeItem = function(key) {
if (!(key in cookies)) return; // ,
// cookie cookies
delete cookies[key];
// .
// indexOf() ,
// ES5.
for(var i = 0; i < keys.length; i++) { //
if (keys[i] === key) { //
keys.splice(i,1); // .
break;
}
}
this.length--; // length
// cookie,
// .
document.cookie = key + "=; max-age=0";
};

641

20.3. userData IE
// cookies
this.clear = function() {
// cookies
for(var i = 0; i < keys.length; i++)
document.cookie = keys[i] + "=; max-age=0";
//
cookies = {};
keys = [];
this.length = 0;
};
}

20.3. userData IE
IE 5
, behavior
. :
var memory = document.createElement("div"); //
memory.id = "_memory"; //
memory.style.display = "none"; //
memory.style.behavior = "url('#default#userData')"; //
document.body.appendChild(memory); //

userData,
load() save(). load() .
,
.
/ ,
getAttribute(). ,
setAttribute() save().
removeAttribute() save().
memory, :
memory.load("myStoredData"); //
var name = memory.getAttribute("username"); //
if (!name) { //
name = prompt(" ?); //
memory.setAtttribute("username", name); //
memory.save("myStoredData"); //
}

, userData,
,
. expires ,
. ,
, ,
100:
var now = (new Date()).getTime(); //
var expires = now + 100 * 24 * 60 * 60 * 1000; //
expires = new Date(expires).toUTCString(); //
memory.expires = expires; //


+ 100

642

20.

, userData IE,
, , ,
. , cookies,
.
userData - path domain
cookies, .
userData ,
cookies, , localStorage sessionStorage.
20.3 getItem(), setItem() removeItem() Sto
rage userData IE. ( , key()
clear(), userData
.)
20.3. Storage
userData IE
function UserDataStorage(maxage) {
//
// behavior userData,
// save() load().
var memory = document.createElement("div"); //
memory.style.display = "none"; //
memory.style.behavior = "url('#default#userData')"; // behavior
document.body.appendChild(memory); //
// maxage, maxage
if (maxage) {
var now = new Date().getTime(); //
var expires = now + maxage * 1000; // maxage
memory.expires = new Date(expires).toUTCString();
}
// , .
// ,
// , save()
memory.load("UserDataStorage"); //
this.getItem = function(key) { //
return memory.getAttribute(key) ||
};
this.setItem = function(key, value) {
memory.setAttribute(key,value); //
memory.save("UserDataStorage"); //
};


null;

this.removeItem = function(key) {
memory.removeAttribute(key); //
memory.save("UserDataStorage"); //
};
}

20.3 IE,
IE,
, IE:

20.4. -

643

<!--[if IE]>
<script src="UserDataStorage.js"></script>
<![endif]-->

20.4.
-
HTML5 (application
cache), -
. localStorage sessionStorage
-,
(HTML, CSS, JavaScript,
..), .
-: ,
. LRU
(least-recently used ),
.
: ,
. ,

(application storage).
-
(,
). -
, , ,
localStorage
.
- 20.4.3,
, .

20.4.1.
,
: , URL , .
HTML , manifest <html>:
<!DOCTYPE HTML>
<html manifest="myapp.appcache">
<head>...</head>
<body>...</body>
</html>

CACHE MANIFEST.
URL- .
URL- URL-
. . , #,
.
, -
. :

644

20.

CACHE MANIFEST
# .
# ,
myapp.html
myapp.js
myapp.css
images/background.png

, .
- - ( HTML, ),
<html manifest=>,
.
,
-.
HTML-, .
: ,
, -
.
, , ,
, -. -

. ,
. ,
, .
.
, ,
. -
.
, .

MIME-

.appcache. ,
-
MIME- text/cache-manifest.
Content-Type
MIME-, .
- MIME, , Apache .htaccess -.

20.4.1.1.
,
. , , URL-

20.4. -

645

. ,
, ,
.
-
. , , ,
CACHE:, .
NETWORK: FALLBACK:. (
, .)
NETWORK: ,
. ,
, URL- . URL- NETWORK:
URL-. , URL-
, .
,
. NETWORK:
URL- *.
, .
, ,
.
FALLBACK: URL- .
, URL, . URL
. URL-, ,
.
URL- ,
, URL-.
-, .
, .

.
:
CACHE MANIFEST
CACHE:
myapp.html
myapp.css
myapp.js
FALLBACK:
videos/ offline_help.html
NETWORK:
cgi/

20.4.2.
-
. ,
. ,
,
. ,

646

20.

.
, JavaScript ,
- ,
. , ,
, , :
CACHE MANIFEST
# MyApp 1 ( ,
# )
MyApp.html
MyApp.js

, , -
, ,
HTTP- 404 Not Found, HTML-
, .
,
, ( ) .
- ,
,
: ,
,
.
,
. :
applicationCache.onupdateready = function() {
var reload = confirm(" , \n" +
" .\n" +
" ?");
if (reload) location.reload();
}

, Appli
cationCache, applicationCache Window.
, , .
updateready, ,
, . 20.4
, ,
.
20.4.
//