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

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:

- -
Books.Ru
ISBN 978-5-93286-215-5, JavaScript. , 6- - Books.Ru
. - ,
.
, - (piracy@symbol.ru),
.

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.
// , ,
// , .
// ,
// false,
// .
function status(msg) {
// id="statusline"
document.getElementById("statusline").innerHTML = msg;
console.log(msg); //
}

20.4. -

// , , .
// "checking".
window.applicationCache.onchecking = function() {
status(" .");
return false;
};
// ,
// "noupdate" .
window.applicationCache.onnoupdate = function() {
status(" .")
return false;
};
// ,
// , .
// "downloading" .
window.applicationCache.ondownloading = function() {
status(" ");
window.progresscount = 0; // "progress"
return false;
};
// "progress",
// .
window.applicationCache.onprogress = function(e) {
// "progress" ( ,
// XHR2), ,
// .
var progress = "";
if (e && e.lengthComputable) // "progress":
progress = " " + Math.round(100*e.loaded/e.total) + "%"
else // -
progress = " (" + ++progresscount + ")"
status(" " + progress);
return false;
};
// ,
// "cached".
window.applicationCache.oncached = function() {
status(" ");
return false;
};
// , ,
// "updateready". ,
// - .
window.applicationCache.onupdateready = function() {
status(" . .");
return false;
};
//
// , "error". ,

647

648

20.

// .
window.applicationCache.onerror = function() {
status(" " +
" ");
return false;
};
// ,
// "obsolete" .
// , .
window.applicationCache.onobsolete = function() {
status(" . " +
" , .");
return false;
};

, HTML- manifest,
checking .
checking :

,
noupdate.


, downloading
, .
progress.
updateready.

, downloading progress
, , .
cached, upda
teready.

,
error.
, , ,
.

,
404 Not Fo
und, obsolete .
, .
20.4 false, ,
.
. (
.)

20.4. -

649

,
applicationCache.status
. :
ApplicationCache.UNCACHED (0)
manifest: .
ApplicationCache.IDLE (1)
,
.
ApplicationCache.CHECKING (2)
.
ApplicationCache.DOWNLOADING (3)
,
.
ApplicationCache.UPDATEREADY (4)
.
ApplicationCache.OBSOLETE (5)
, .
ApplicationCache . update()
.
(
), .
swapCache() . , ,
, -
. ,
. ,
. , -
: , , XMLHttpRequest
, .
, , ,
.
swapCache() ,
. ,
: HTML-, ,
, , .
.
,
, .
, , ,
, .
noupdate, .
downloading,
, .
updateready, swapCache()
.

650

20.

, swapCache() ,
status ApplicationCache.UPDATEREADY ApplicationCache.
OBSOLETE. ( swapCache(), status OBSOLETE,
, .)
swapCache(), status
, .

20.4.3. -
-,
,
.
,
. -
:
. ,
, ,
localStorage
, .

- ,
.
, -
, ,
.
navigator.onLine.
, online offline
Window.
-,
. PermaNote
, ,
, localStorage ,
.1 PermaNote

, ,

- . PermaNote
. 20.5 .
, URL note
: URL- .
20.5. permanote.appcache
CACHE MANIFEST
# PermaNote v8
permanote.html
1

Halfnote,
(Aaron Boodman). Halfnote
-.

20.4. -

651

permanote.js
NETWORK:
note

20.6 PermaNote: HTML-,


.
<textarea>
. , <html>
manifest.
20.6. permanote.html
<!DOCTYPE HTML>
<html manifest="permanote.appcache">
<head>
<title> PermaNote</title>
<script src="permanote.js"></script>
<style>
#editor { width: 100%; height: 250px; }
#statusline { width: 100%; }
</style>
</head>
<body>
<div id="toolbar">
<button id="savebutton" onclick="save()"></button>
<button onclick="sync()"></button>
<button onclick="applicationCache.update()"> </button>
</div>
<textarea id="editor"></textarea>
<div id="statusline"></div>
</body>
</html>

, 20.7 JavaScript,
- PermaNote. status()
, save()
sync()
. save() sync()
HTTP, 18. ( ,
save() HTTP- PUT
POST.)
20.7
.
, :
onload
,
, .
save() sync() HTTP-
onload XMLHttpRequest, ,
.

652

20.

onbeforeunload
,
.
oninput
, <textarea> ,
localStorage, .
5 , .
onoffline
,
.
ononline
,
.
onupdateready
,
, .
onnoupdate
, ,
.
, PermaNote,
20.7 .
20.7. permanote.js
//
var editor, statusline, savebutton, idletimer;
//
window.onload = function() {
// ,
if (localStorage.note == null) localStorage.note = "";
if (localStorage.lastModified == null) localStorage.lastModified = 0;
if (localStorage.lastSaved == null) localStorage.lastSaved = 0;
// , .
// .
editor = document.getElementById("editor");
statusline = document.getElementById("statusline");
savebutton = document.getElementById("savebutton");
editor.value = localStorage.note; //
editor.disabled = true; // .
// textarea
editor.addEventListener("input",
function (e) {
// localStorage
localStorage.note = editor.value;
localStorage.lastModified = Date.now();
//

20.4. -
if (idletimer) clearTimeout(idletimer);
idletimer = setTimeout(save, 5000);
//
savebutton.disabled = false;
},
false);
//
sync();
};
//
window.onbeforeunload = function() {
if (localStorage.lastModified > localStorage.lastSaved)
save();
};
//
window.onoffline = function() { status(" "); }
// .
window.ononline = function() { sync(); };
// , .
// ,
// location.reload()
window.applicationCache.onupdateready = function() {
status(" . " +
" , ");
};
// , .
window.applicationCache.onnoupdate = function() {
status(" .");
};
//
function status(msg) { statusline.innerHTML = msg; }
// ( ).
// 5 .
function save() {
if (idletimer) clearTimeout(idletimer);
idletimer = null;
if (navigator.onLine) {
var xhr = new XMLHttpRequest();
xhr.open("PUT", "/note");
xhr.send(editor.value);
xhr.onload = function() {
localStorage.lastSaved = Date.now();
savebutton.disabled = true;
};
}
}
// . ,
// .

653

654

20.

function sync() {
if (navigator.onLine) {
var xhr = new XMLHttpRequest();
xhr.open("GET", "/note");
xhr.send();
xhr.onload = function() {
var remoteModTime = 0;
if (xhr.status == 200) {
var remoteModTime = xhr.getResponseHeader("Last-Modified");
remoteModTime = new Date(remoteModTime).getTime();
}
if (remoteModTime > localStorage.lastModified) {
status(" .");
var useit =
confirm(" \n" +
". Ok, \n" +
" , \n"+
", \n"+
" ");
var now = Date.now();
if (useit) {
editor.value = localStorage.note = xhr.responseText;
localStorage.lastSaved = now;
status(" .");
}
else
status(" .");
localStorage.lastModified = now;
}
else
status(" .");
if (localStorage.lastModified > localStorage.lastSaved) {
save();
}
editor.disabled = false; //
editor.focus(); //
}
}
else { //
status(" ");
editor.disabled = false;
editor.focus();
}
}

21


21.

, ,
- . 21.1
JavaScript,
,
. 21.2 <audio>
<video>, HTML5,
JavaScript.
, , -
,
.

:
, ,
, ,
.

. ,

.

-,
, .
21.3 Scalable Vector Graphics, SVG. SVG
, XML,
. SVG
JavaScript DOM.
21.4 <canvas>, HTML5,
JavaScript,

656

21.

. <canvas>
, .

21.1.
- <img>.
HTML-, <img> :
URL- src (
) . ( ,
, ,
.)
HTML-
.

. ,
.
( CSS :hover,
.)
HTML ,
:
<img src="images/help.gif"
onmouseover="this.src='images/help_rollover.gif'"
onmouseout="this.src='images/help.gif'">

<img> src,
.

, <img> <a>
onclick.
, ( )
. ,
,
. JavaScript
:
, Image Image().
, src URL-, .
, ,
, . , URL ,
, .
,
, ,
,
. ,
:
<script>(new Image()).src = "images/help_rollover.gif";</script>
<img src="images/help.gif"

21.1.

657

onmouseover="this.src='images/help_rollover.gif'"
onmouseout="this.src='images/help.gif'">

21.1.1.
<script>
JavaScript-
. Java
Script-: ,
HTML. 21.1 ,
datarollover (15.4.3) <img>. ,
onLoad() 13.5.
document.images[] (15.2.3),
<img> .
21.1.
/**
* rollover.js: .
*
* HTML-
* data-rollover <img>, URL-
* . :
*
* <img src="normal_image.png" data-rollover="rollover_image.png">
*
* , onLoad.js
*/
onLoad(function() { // :
// , data-rollover
for(var i = 0; i < document.images.length; i++) {
var img = document.images[i];
var rollover = img.getAttribute("data-rollover");
if (!rollover) continue; // data-rollover
//
(new Image()).src = rollover;
// URL-
//
img.setAttribute("data-rollout", img.src);
// ,
//
img.onmouseover = function() {
this.src = this.getAttribute("data-rollover");
};
img.onmouseout = function() {
this.src = this.getAttribute("data-rollout");
};
}
});

658

21.

21.2. -
HTML5 <audio> <video>,
, <img>.
HTML5
( Flash), HTML- -
:
<audio src="background_music.mp3"/>
<video src="news.mov" width=320 height=240/>

,
.
- , ,
<source>,
:
<audio id="music">
<source src="music.mp3" type="audio/mpeg">
<source src="music.ogg" type='audio/ogg; codec="vorbis"'>
</audio>

, <source> :
</source>,
/>.
, <audio> <video>,
. , ,
. ,
(, <object>,
Flash):
<video id="news" width=640 height=480 controls preload>
<!-- WebM Firefox Chrome -->
<source src="news.webm" type='video/webm; codecs="vp8, vorbis"'>
<!-- H.264 IE Safari -->
<source src="news.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
<!-- Flash -->
<object width=640 height=480 type="application/x-shockwave-flash"
data="flash_movie_player.swf">
<!-- Flash -->
<!-- , -->
<div> video Flash .</div>
</object>
</video>

<audio> <video> controls.


( JavaScript- true),
,
, .. , <audio> <video>
,
,
-
. ,

21.2. -

659

<audio> <video>
( , <video>
width height), ,
, .

,

, HTML5.
,
.
JavaScript,
- .

Audio()
<audio> ,
controls. ,
Image(),
, HTML5,
Audio(),
URL- :
new Audio("chime.wav").play(); //

Audio() ,
<audio>
document.createElement("audio"). ,
:
Video().

21.2.1.
,
, MIME-
( codec) canPlayType().
( ),
.
maybe () probably (). -
, probably (),
:
var a = new Audio();
if (a.canPlayType("audio/wav")) {
a.src = "soundeffect.wav";
a.play();
}

660

21.

src ,
. (
, preload auto.)
src

. src
<source>,
, ,
<source>, ,
load().

21.2.2.
<audio> <video> play()
pause(), :
// ,
window.addEventListener("load", function() {
document.getElementById("music").play();
}, false);



currentTime. ,
,
. ( initialTime duration
currentTime;
.)
volume
0 ( ) 1 ( ). muted
true, , false,
.
playbackRate . 1,0
. 1
, 0 1
.
,
. <audio> <video>
defaultPlaybackRate. , play(),
defaultPlaybackRate playbackRate.
, currentTime, volume, muted playbackRate
.
<audio> <video> controls,
, .
, muted current
Time, , .
HTML- controls, loop, preload autoplay
, JavaScript-
. controls ,

21.2. -

661

. true,
, false, . loop
, (true)
(false). preload ,
,
. none ,
. metadata ,
, , ,
. preload
. auto ,
,
. , autoplay ,
, .
autoplay true ,
.

21.2.3.

<audio> <video> ,
, .
paused true, .
seeking true,
. ended true,
. ( ended
true, loop true.)
duration
. , ,
NaN.
, , -,
Infinity.
initialTime
.
0.
, .
currentTime
initialTime.

.
played ,
. buffered
, , seekable
,
. ( ,
currentTime duration,
.)
played, buffered seekable TimeRanges.
length,

662

21.

, start() end(), ()
. ,
, , start(0) end(0). ,
, ,
, , ,
:
var percent_loaded = Math.floor(song.buffered.end(0) / song.duration * 100);

, , readyState, networkState error,


<audio> <video>.
,
. ,
( ).
, :
if (song.readyState === song.HAVE_ENOUGH_DATA) song.play();

readyState ,
, , , .
:

HAVE_NOTHING

HAVE_METADATA

,

. ,

, ,
currentTime,
currentTime.

HAVE_CURRENT_DATA 2

currentTime
, ,
.
, ,
. - .

HAVE_FUTURE_DATA 3

,
, ,

.

HAVE_ENOUGH_DATA 4

, ,
, , .

networkState , ( , )
:

NETWORK_EMPTY

.
, ,
src.

663

21.2. -

NETWORK_IDLE

.
,
. ,
, preload none

.

NETWORK_LOADING

NETWORK_NO_SOURCE

,
.

,
error <audio> <video>.
error null.
code, .
:

MEDIA_ERR_ABORTED

MEDIA_ERR_NETWORK

,
.

MEDIA_ERR_DECODE

,

.

MEDIA_ERR_SRC_NOT_SUPPORTED

,
src, ,
.

error , :
if (song.error.code == song.error.MEDIA_ERR_DECODE)
alert(" : .");

21.2.4
<audio> <video>
,
, ,
. ,
, . HTML-
, <audio> <video>
.
, .
22 ,
, .
,
<audio> <video> addEventListener().

664

21.

,
. networkState NETWORK_LOADING.
progress
. networkState
NETWORK_LOADING. 2
8 .
loadedmetadata ,
. readyState
HAVE_METADATA.
,
loadeddata
readyState HAVE_CURRENT_DATA.
, , ,
canplay
,
. readyState HAVE_FUTURE_DATA.
canplaythrough ,

. readyState HAVE_ENOUGH_DATA.

suspend
. networkState NETWORK_IDLE.
, .
stalled
networkState NETWORK_LOADING.
play
play()
- autoplay.
, playing.
waiting.
-
waiting
.
, playing.
.
playing
timeupdate
currentTime.
4 60
.
pause
pause(), .
,
seeking
,
. seeking true.
seeked
seeking false.
.
ended
loadstart

durationchange
volumechange
ratechange
abort
error

emptied

duration.
volume muted.
playbackRate defaultPlaybackRate.
.
. error.code MEDIA_ERR_ABORTED.
-
. error.code ,
MEDIA_ERR_ABORTED.
error abort networkState
NETWORK_EMPTY.

21.3. SVG

665

21.3. SVG
(SVG) XML
.
, GIF, JPEG
PNG, . SVG
, ( )
, ,
. SVG- :
<!-- -->
<svg xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 1000 1000"> <!-- -->
<defs> <!-- -->
<linearGradient id="fade"> <!-- "fade" -->
<stop offset="0%" stop-color="#008"/> <!-- - -->
<stop offset="100%" stop-color="#ccf"/><!-- --->
</linearGradient>
</defs>
<!-
-->
<rect x="100" y="200" width="800" height="600"
stroke="black" stroke-width="25" fill="url(#fade)"/>
</svg>

.21.1 SVG-.

.21.1. SVG

SVG .
,
. SVG JavaScript-
CSS-,

666

21.

. , Java
Script- ( HTML-, SVG-)
SVG.
SVG- SVG.
,
, W3C
http://www.w3.org/TR/SVG/. :
(DOM) SVG-.
SVG-
XML DOM, SVG DOM .
-, IE,
SVG ( IE9).
SVG-
<img>. ( Firefox3.6)

<object>:
<object data="sample.svg" type="image/svg+xml" width="100" height="100"/>

<img> <object> SVG


, ,
JavaScript, .
SVG-
.
SVG XML,
XHTML-, :
<?xml version="1.0"?>
<!-- HTML , SVG - "svg:" -->
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:svg="http://www.w3.org/2000/svg">
<body>
: <svg:svg width="10" height="10">
<svg:rect x="0" y="0" width="10" height="10" fill="red"/>
</svg:svg>
: <svg:svg width="10" height="10">
<svg:circle cx="5" cy="5" r="5" fill="blue"/>
</svg:svg>
</body>
</html>

, IE. .21.2
, Firefox XHTML-.

.21.2. SVG- XHTML-

21.3. SVG

667

HTML5 XML HTML


SVG ( MathML) HTML, :
<!DOCTYPE html>
<html>
<body>
: <svg width="10" height="10">
<rect x="0" y="0" width="10" height="10" fill="red"/>
</svg>
: <svg width="10" height="10">
<circle cx="5" cy="5" r="5" fill="blue"/>
</svg>
</body>
</html>

SVG-
HTML .
SVG XML, SVG-
DOM
XML-. 21.2 pieChart(),
SVG- ,
, .21.3.

.21.3. SVG, JavaScript-


21.2. JavaScript SVG
/**
* <svg> .
* :
* data: , .
* width,height: SVG-
* cx, cy, r:
* colors: HTML,
* labels: ,

668

21.

* lx, ly:
* :
* <svg>, .
* .
*/
function pieChart(data, width, height, cx, cy, r, colors, labels, lx, ly) {
// XML svg
var svgns = "http://www.w3.org/2000/svg";
// <svg>,
var chart = document.createElementNS(svgns, "svg:svg");
chart.setAttribute("width", width);
chart.setAttribute("height", height);
chart.setAttribute("viewBox", "0 0 " + width + " " + height);
// ,
var total = 0;
for(var i = 0; i < data.length; i++) total += data[i];
// . .
var angles = []
for(var i = 0; i < data.length; i++) angles[i] = data[i]/total*Math.PI*2;
// .
startangle = 0;
for(var i = 0; i < data.length; i++) {
// ,
var endangle = startangle + angles[i];
// , ,
// . 0
// ,
// .
var x1 = cx + r * Math.sin(startangle);
var y1 = cy - r * Math.cos(startangle);
var x2 = cx + r * Math.sin(endangle);
var y2 = cy - r * Math.cos(endangle);
// , .
// SVG-
var big = 0;
if (endangle - startangle > Math.PI) big = 1;
// <svg:path>.
// , createElementNS()
var path = document.createElementNS(svgns, "path");
// ,
var d = "M " + cx + "," + cy + //
" L " + x1 + "," + y1 + // (x1,y1)
" A " + r + "," + r + // r
" 0 " + big + " 1 " + // ...
x2 + "," + y2 + // (x2,y2)
" Z"; // (cx,cy)
// <svg:path>
path.setAttribute("d", d); //
path.setAttribute("fill", colors[i]); //
path.setAttribute("stroke", "black"); // -

21.3. SVG

669

path.setAttribute("stroke-width", "2"); // 2
chart.appendChild(path); //
// ,
startangle = endangle;
//
var icon = document.createElementNS(svgns, "rect");
icon.setAttribute("x", lx); //
icon.setAttribute("y", ly + 30*i);
icon.setAttribute("width", 20); //
icon.setAttribute("height", 20);
icon.setAttribute("fill", colors[i]); // ,
icon.setAttribute("stroke", "black"); // .
icon.setAttribute("stroke-width", "2");
chart.appendChild(icon); //
//
var label = document.createElementNS(svgns, "text");
label.setAttribute("x", lx + 30); //
label.setAttribute("y", ly + 30*i + 18);
// CSS-
label.setAttribute("font-family", "sans-serif");
label.setAttribute("font-size", "16");
// DOM- <svg:text>
label.appendChild(document.createTextNode(labels[i]));
chart.appendChild(label); //
}
return chart;
}

21.2 .

.
, SVG-
. ,
HTML5, SVG XML
createElement() SVG
createElementNS().
,
.
<svg:path>. SVG- ,
. d
<svg:path>.
, , . ,
M move to ( ),
X Y . L line to (
); ,
. , A,
(arc). ,
. ,
http://www.w3.org/TR/SVG/.

670

21.

, pieChart() <svg>,
, .
, . ,
.21.3, :
<html>
<head>
<script src="PieChart.js"></script>
</head>
<body onload="document.body.appendChild(
pieChart([12, 23, 34, 45], 640, 400, 200, 200, 150,
['','','',''],
['','', '', ''], 400, 100));
">
</body>
</html>

21.3 SVG-:
SVG (.21.4).
SVG- ,
SVG- , HTML-.
SVG- <line>,
. ,
12:00.
, JavaScript,
transform <line>
, .

.21.4. SVG-

, 21.3 SVG
HTML5 XML, XHTML . , ,
SVG.
HTML- XHTML, SVG.
21.3.
SVG-
<!DOCTYPE HTML>
<html>
<head>
<title>Analog Clock</title>

21.3. SVG
<script>
function updateTime() { // SVG-
//
var now = new Date(); //
var min = now.getMinutes(); //
var hour = (now.getHours() % 12) + min/60; //
var minangle = min*6; // 6
var hourangle = hour*30; // 30
// SVG-
var minhand = document.getElementById("minutehand");
var hourhand = document.getElementById("hourhand");
// SVG-
minhand.setAttribute("transform", "rotate(" + minangle + ",50,50)");
hourhand.setAttribute("transform", "rotate(" + hourangle + ",50,50)");
// 1
setTimeout(updateTime, 60000);
}
</script>
<style>
/* CSS- SVG-, */
#clock { /* */
stroke: black; /* */
stroke-linecap: round; /* */
fill: #eef; /* , - */
}
#face { stroke-width: 3px;} /* */
#ticks { stroke-width: 2; } /* */
#hourhand {stroke-width: 5px;} /* */
#minutehand {stroke-width: 3px;} /* */
#numbers { /* */
font-family: sans-serif; font-size: 7pt; font-weight: bold;
text-anchor: middle; stroke: none; fill: black;
}
</style>
</head>
<body onload="updateTime()">
<!-- viewBox - , width height - -->
<svg id="clock" viewBox="0 0 100 100" width="500" height="500">
<defs> <!-- -->
<filter id="shadow" x="-50%" y="-50%" width="200%" height="200%">
<feGaussianBlur in="SourceAlpha" stdDeviation="1" result="blur" />
<feOffset in="blur" dx="1" dy="1" result="shadow" />
<feMerge>
<feMergeNode in="SourceGraphic"/><feMergeNode in="shadow"/>
</feMerge>
</filter>
</defs>
<circle id="face" cx="50" cy="50" r="45"/> <!-- -->
<g id="ticks"> <!-- 12 -->
<line x1='50' y1='5.000' x2='50.00' y2='10.00'/>
<line x1='72.50' y1='11.03' x2='70.00' y2='15.36'/>
<line x1='88.97' y1='27.50' x2='84.64' y2='30.00'/>
<line x1='95.00' y1='50.00' x2='90.00' y2='50.00'/>

671

672

21.

<line x1='88.97' y1='72.50' x2='84.64' y2='70.00'/>


<line x1='72.50' y1='88.97' x2='70.00' y2='84.64'/>
<line x1='50.00' y1='95.00' x2='50.00' y2='90.00'/>
<line x1='27.50' y1='88.97' x2='30.00' y2='84.64'/>
<line x1='11.03' y1='72.50' x2='15.36' y2='70.00'/>
<line x1='5.000' y1='50.00' x2='10.00' y2='50.00'/>
<line x1='11.03' y1='27.50' x2='15.36' y2='30.00'/>
<line x1='27.50' y1='11.03' x2='30.00' y2='15.36'/>
</g>
<g id="numbers"> <!-- -->
<text x="50" y="18">12</text><text x="85" y="53">3</text>
<text x="50" y="88">6</text><text x="15" y="53">9</text>
</g>
<!-- , . . -->
<g id="hands" filter="url(#shadow)"> <!-- -->
<line id="hourhand" x1="50" y1="50" x2="50" y2="24"/>
<line id="minutehand" x1="50" y1="50" x2="50" y2="20"/>
</g>
</svg>
</body>
</html>

21.4.
<canvas>
<canvas> ,

JavaScript . <canvas>
HTML5, .
Apple Safari1.3 Firefox,
1.5, Opera, 9.
Chrome. <canvas> IE
IE9, IE6, 7 8
ExplorerCanvas,
http://code.google.com/p/explorercanvas/.
<canvas> SVG
, <canvas>
, SVG
XML-.
: .
,
. , SVG- .
, <canvas>,
, .
Canvas JavaScript,
(
SVG), .
IV Canvas, CanvasRenderingContext2D
.

21.4. <canvas>

673

<canvas>


<canvas>. WebGL
JavaScript
OpenGL.
, getContext() <canvas>
webgl. WebGL ,
, : -,
, ,
WebGL, WebGL.

Canvas <canvas>,
, getContext()
, . getContext() 2d
CanvasRenderingContext2D,
. , <canvas>
.
, Can
vasRenderingContext2D , .
, Canvas,
CanvasRenderingContext2D.
HTML-,
Canvas.
<canvas>, .21.2:
<body>
: <canvas id="square" width=10 height=10></canvas>.
: <canvas id="circle" width=10 height=10></canvas>.
<script>
var canvas = document.getElementById("square"); // canvas
var context = canvas.getContext("2d"); // 2-
context.fillStyle = "#f00"; // -
context.fillRect(0,0,10,10); //
canvas = document.getElementById("circle"); //
context = canvas.getContext("2d"); //
context.beginPath(); //
context.arc(5, 5, 5, 0, 2*Math.PI, true); //
context.fillStyle = "#00f"; //
context.fill(); //
</script>
</body>

canvas

""

-

, SVG
,
. Canvas .
,

674

21.

, beginPath() arc(),
. ,
, , fill().

, fillStyle. :
,
.

<canvas>
.
, <canvas> ,
.
Canvas.

.
,
.
,
.
<canvas>.
,
.
.
( )
<canvas>
.
,
() .
, ,
<canvas>.
, ,
<canvas>.
,
<canvas>
(sparklines).
<canvas>, ,
c. CanvasRenderingContext2D
<canvas>,
. ,
HTML, <canvas> width
height, , c:
var canvas = document.getElementById("my_canvas_id");
var c = canvas.getContext('2d');

21.4. <canvas>

675

, , JavaScript,
<canvas> ,
, .

21.4.1.
<canvas>
, ,
(path).
.
, (, ,
). beginPath().
moveTo().
moveTo()
, lineTo(). ,
:
c.beginPath(); //
c.moveTo(100, 100); //
c.lineTo(200, 200); //
c.lineTo(100, 200); //


(100,100)
, (100,100) (200,200)
, (200,200) (100,200)

.
, stroke(),
, , fill():
c.fill(); //
c.stroke(); //

( ,
) ,
.21.5.

.21.5. ,

, , ,
. ,
. . fill()
,
.
,
.
,
closePath(),
. ( lineTo(100,100),

676

21.

, .
,
closePath().)
, stroke() fill().
-, .
, :
c.moveTo(300,100); // (300,100);
c.lineTo(300,200); // (300,200);

stroke(),
.
-, , stroke() fill()
: fill(),
, stroke().
,
beginPath().
,
.
21.4
moveTo(), lineTo() closePath()
fill() stroke()
. , .21.6.

.21.6.
21.4.
moveTo(), lineTo() closePath()
// n ,
// (x,y) r. ,
// .
// angle.
// , true.
function polygon(c,n,x,y,r,angle,counterclockwise) {
angle = angle || 0;
counterclockwise = counterclockwise || false;
c.moveTo(x + r*Math.sin(angle), //
y - r*Math.cos(angle)); // . .
var delta = 2*Math.PI/n; //
for(var i = 1; i < n; i++) { //
angle += counterclockwise?-delta:delta; //
c.lineTo(x + r*Math.sin(angle), // .
y - r*Math.cos(angle));
}

21.4. <canvas>

677

c.closePath(); //
}
// ,
c.beginPath();
polygon(c, 3, 50, 70, 50); //
polygon(c, 4, 150, 60, 50, Math.PI/4); //
polygon(c, 5, 255, 55, 50); //
polygon(c, 6, 365, 53, 50, Math.PI/6); //
polygon(c, 4, 365, 53, 20, Math.PI/4, true); //
//
c.fillStyle =
c.strokeStyle
c.lineWidth =

,
"#ccc"; // -
= "#008"; // -
5; // .

// ( )
//
c.fill(); //
c.stroke(); //

,
. ,
. (
), <canvas> ,
, .
<canvas> ,
(nonzero winding rule).
- ,
:
,
.
, fill() .


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

678

21.

21.4.2.
21.4 fillStyle, strokeStyle lineWidth
<canvas>.
, , fill(); ,
stroke(); , stroke(). ,
fill() stroke(),
<canvas>. ,
, , ,
, ,
strokeStyle fillStyle .

Canvas
, CSS HTML-.
Canvas 15
CanvasRenderingContext2D. . 21.1
.
21.1. Canvas

fillStyle

, ,

font

CSS

globalAlpha

globalCompositeOperation
lineCap

lineJoin

lineWidth

miterLimit

textAlign

textBaseline

shadowBlur

shadowColor

shadowOffsetX

shadowOffsetY

strokeStyle

, ,

Canvas
, getContext()
, . ,

. ,
<canvas> . <canvas>
, getContext()
CanvasRenderingContext2D.

21.4. <canvas>

679

, Canvas
,
,
. save()
. restore()
.
, . 21.1,
(
). ,

.
,
, ,
21.5.
21.5.
// ,
// .
CanvasRenderingContext2D.prototype.revert = function() {
this.restore(); // .
this.save(); // , .
return this; // .
};
// o.
// , , .
// , .
CanvasRenderingContext2D.prototype.attrs = function(o) {
if (o) {
for(var a in o) // o
this[a] = o[a]; //
return this; //
}
else return {
fillStyle: this.fillStyle, font: this.font,
globalAlpha: this.globalAlpha,
globalCompositeOperation: this.globalCompositeOperation,
lineCap: this.lineCap, lineJoin: this.lineJoin,
lineWidth: this.lineWidth, miterLimit: this.miterLimit,
textAlign: this.textAlign, textBaseline: this.textBaseline,
shadowBlur: this.shadowBlur, shadowColor: this.shadowColor,
shadowOffsetX: this.shadowOffsetX, shadowOffsetY: this.shadowOffsetY,
strokeStyle: this.strokeStyle
};
};

21.4.3.
width height <canvas> width
height Canvas .
(0,0) . X
, Y .

680

21.

,

Canvas .
,
.
width height Canvas (
) ,
(
) .
,
,
. ( )
CSS-. CSS-
.
CSS-. ,
, ,
.
, (21.4.14),
CSS-
,
.
<canvas> (CSS-
), HTML- width height. ,
HTML-, <canvas> ,
CSS- width height.
,
, CSS-
. CSS-
, ,

.
, .
.

21.4.4.
,
, X
, Y .
CSS- (
).
(
) .

.
. ,
, ,
.

21.4. <canvas>

681


.
setTransform()
,
, .
.21.7.
, ,
. ,
, . ,
, .
translate() , ,
. rotate()
. ( Canvas
. ,
180 Math.PI.) scale()
X Y.
scale()
,
.
.21.7: translate()
, scale() Y ,
Y .

, . ,
, !

.21.7.

682

21.

21.4.4.1.
, ,
, translate(), rotate() scale()
, .21.7.
,
, (x,y)
(x',y') .
c.translate(dx,dy) :
x' = x + dx; // 0 X
// dx
y' = y + dy;


. c.scale(sx,sy) :
x' = sx * x;
y' = sy * y;

. c.rotate(a)
:
x' = x * cos(a) - y * sin(a);
y' = y * cos(a) + x * sin(a);

,
. ,
, .
(x,y)
(x'',y'') ,
,
(x', y') ,
, ,
(x'',y'').
:
x'' = sx*x + dx;
y'' = sy*y + dy;

scale(),
translate(), :
x'' = sx*(x + dx);
y'' = sy*(y + dy);


,
.

, .
, ,
.
,

21.4. <canvas>

683

, , .
a f,
:
x' = ax + cy + e
y' = bx + dy + f

,
transform(). .21.7

transform(), :
// :
// x' = x + kx*y;
// y' = y + ky*x;
function shear(c,kx,ky) { c.transform(1, ky, kx, 1, 0, 0); }
// theta (x,y).
// translate,rotate,translate
function rotateAbout(c,theta,x,y) {
var ct = Math.cos(theta), st = Math.sin(theta);
c.transform(ct, -st, st, ct, -x*ct-y*st+x, x*st-y*ct+y);
}

setTransform() , transform(),


. setTransform()
:
c.save(); //
c.setTransform(1,0,0,1,0,0); //
// CSS-
c.restore(); //

21.4.4.2.
21.6 ,
, translate(),
rotate() scale() .
. 21.8,
0, 1, 2, 3 4.

.21.8.

,
,
.

684

21.

, ,
lineTo(). .21.8
:
c.lineTo(len, 0);

len ,
,
, .
21.6.

var deg = Math.PI/180; //
// n- c,
// (x,y), len.
function snowflake(c, n, x, y, len) {
c.save(); //
c.translate(x,y); //
c.moveTo(0,0); //
leg(n); //
c.rotate(-120*deg); // 120
leg(n); //
c.rotate(-120*deg); //
leg(n); //
c.closePath(); //
c.restore(); //
// n- .
// ,
// (0,0).
// , rotate().
function leg(n) {
c.save(); //
if (n == 0) { // :
c.lineTo(len, 0); //
} // _ _
else { // : 4 : \/
c.scale(1/3,1/3); // 3
leg(n-1); //
c.rotate(60*deg); // 60
leg(n-1); //
c.rotate(-120*deg); // 120
leg(n-1); //
c.rotate(60*deg); //
leg(n-1); //
}
c.restore(); //
c.translate(len, 0); // (0,0)
}
}
snowflake(c,0,5,115,125); //
//
snowflake(c,1,145,115,125); // -

21.4. <canvas>

685

snowflake(c,2,285,115,125); // .
snowflake(c,3,425,115,125);
snowflake(c,4,565,115,125); // !
c.stroke(); //

21.4.5.
,
, . ,
21.4.1, ,
. CanvasRenderingContext2D
,
:
arc()
.

,
. : X Y
, ,
( )
.
arcTo()
, arc(),
.
arcTo() P1 P2 . ,
, , ,
P1 P1 P2,
. , ,
.
0, ,
P1. ,
P1
, ,
P2.
bezierCurveTo()
P
.
C1 C2. ( )
C1. ( P)
C2.
. P .
quadraticCurveTo()
bezierCurveTo(),
.
, ,
.21.9.

686

21.

.21.9. ,

21.7 ,
.21.9. , ,
Canvas.
.
21.7.
//
function rads(x) { return Math.PI*x/180; }
// . ,
// . ,
// , .
c.beginPath();
c.arc(75,100,50, // (75,100), 50
0,rads(360),false); // 0 360
// . x.
// , arc() .
c.moveTo(200, 100); //
c.arc(200, 100, 50, //
rads(-60), rads(0), // -60 , 0
false); // false
c.closePath(); //
// ,
c.moveTo(325, 100);
c.arc(325, 100, 50, rads(-60), rads(0), true); //
c.closePath();
// arcTo() .
// (400,50), .
c.moveTo(450, 50); // .
c.arcTo(500,50,500,150,30); // .
c.arcTo(500,150,400,150,20); // .
c.arcTo(400,150,400,50,10); // .
c.arcTo(400,50,500,50,0); // .
c.closePath(); // , .
// :
c.moveTo(75, 250); // (75,250)
c.quadraticCurveTo(100,200, 175, 250); // (175,250)
c.fillRect(100-3,200-3,6,6); // (100,200)

21.4. <canvas>

687

//
c.moveTo(200, 250); // (200,250)
c.bezierCurveTo(220,220,280,280,300,250); // (300,250)
c.fillRect(220-3,220-3,6,6); //
c.fillRect(280-3,280-3,6,6);
//
c.fillStyle = "#aaa"; //
c.lineWidth = 5; // ( ) 5
c.fill(); //
c.stroke(); //

21.4.6.
CanvasRenderingContext2D
. , fillRect(), 21.7
.
,
, , .
,
.
fillRect()
fillStyle. strokeRect()
, strokeStyle
. clearRect() fillRect(),

( ). ,
,
.
rect(),
:
. ,
, .

21.4.7. , ,
strokeStyle fillStyle
. ,
,
CanvasPattern CanvasGradient,

. , globalAlpha,
, .
, ,
HTML41, CSS:
context.strokeStyle = "blue"; //
context.fillStyle = "#aaa"; //
1

Aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver, teal,
white yellow.

688

21.

strokeStyle fillStyle #000000,


.
CSS3 RGB, RGBA, HSL HSLA
RGB. :
var colors = [
"#f44", //
"#44ff44", //
"rgb(60, 60, 255)", //
"rgb(100%, 25%, 100%)", //
"rgba(100%, 25%, 100%, 0.5)",//
"rgba(0,0,0,0)", //
"transparent", //
"hsl(60, 100%, 50%)", //
"hsl(60, 75%, 50%)", //
"hsl(60, 100%, 75%)", //
"hsl(60, 100%, 25%)", //
"hsla(60, 100%, 50%, 0.5)", //
];

RGB:
RRGGBB:
RGB 0-255:
RGB :
RGB 0-1:




,
,
, 50%

HSL ,
(hue), (saturation) (lightness). (hue)
. 0 , 60
, 120 , 180 , 240 , 300 360
.
. 0% .
.
HSL 100- ,
0% . HSLA ,
HSL, -,
0.0 () 1.0 ().
,
- ,
(),
globalAlpha.
- , ,
globalAlpha. 1
. globalAlpha 0,
.
0.5,
. ,
50%, 25%. globalAlpha
, ,
, , ( )
, ,
Canvas, 21.4.13.
( ),

. .21.10 ,

.

21.4. <canvas>

689

,
.

.21.10.


, fillStyle strokeStyle
CanvasPattern, createPattern() :
var image = document.getElementById("myimage");
c.fillStyle = c.createPattern(image, "repeat");

createPattern() ,
. <img>, <canvas>
<video> ( Image, Image()).
repeat,
, ,
repeat-x, repeat-y no-repeat.
,
<canvas> <canvas> (
):
var offscreen = document.createElement("canvas"); //
offscreen.width = offscreen.height = 10; //
offscreen.getContext("2d").strokeRect(0,0,6,6); //
//
var pattern = c.createPattern(offscreen,"repeat");//

690

21.

( ) ,
fillStyle ( strokeStyle) CanvasGradient,
createLinearGradient() createRadialGradient() .
,
, .
CanvasGradient. cre
ateLinearGradient() , (
),
. createRadialGradient()
. (
, .)

, .
CanvasGradient
, addColorStop()
CanvasGradient.
0.0 1.0. , CSS.
, ,
. , 0.0,
, , 1.0,
. ,
.
. :
// , (, )
var bgfade = c.createLinearGradient(0,0,canvas.width,canvas.height);
bgfade.addColorStop(0.0, "#88f"); // -
bgfade.addColorStop(1.0, "#fff"); //
// .
// .
var peekhole = c.createRadialGradient(300,300,100, 300,300,300);
peekhole.addColorStop(0.0, "transparent"); //
peekhole.addColorStop(0.7, "rgba(100,100,100,.9)"); //
peekhole.addColorStop(1.0, "rgba(0,0,0,0)"); //

, .
.
,
, . , ,
, (0,0) (100, 100),
,
(0,0,100,100).
, . 21.10,
pattern bgfade peekhole :
c.fillStyle = bgfade; //
c.fillRect(0,0,600,600); //
c.strokeStyle = pattern; //
c.lineWidth = 100; //
c.strokeRect(100,100,400,400); //

21.4. <canvas>

691

c.fillStyle = peekhole; //
c.fillRect(0,0,600,600); //

21.4.8.
lineWidth, ,
stroke() strokeRect(). lineWidth ( ,
strokeStyle) ,
.
lineWidth 1,
, 1. (
,
1).
lineWidth,
. ,
stroke(), , lineWidth
. ,
, ,
, ,
. , ,
, save() clip()
(21.4.10), stroke() restore().
- ,
.21.7, .
scale(2,1), X
Y,
, lineWidth.
, lineWidth
, stroke(),
lineTo() .

, .
,
.
.21.11.
,
.

.21.11. lineCap lineJoin

lineCap ,
. butt ( )

692

21.

. square
.
round
(
).
lineJoin ,
. miter,
,
. round ,
bevel .
, , miterLimit,
, lineJoin miter.
,
,
. miterLimit
.
, miterLimit,
.

21.4.9.
fillText(),
, ( ),
fillStyle.
,
strokeText() (
.21.13). ,
, X Y .

. .21.7,
.
font ,
.
CSS- font. :
"48pt sans-serif"
"bold 18px Times Roman"
"italic 12pt monospaced"
"bolder smaller serif" // , <canvas>

textAlign
X, fillText() strokeText(). text
Baseline
Y. .21.12 .
,
(x,y),
fillText().
textAlign start. ,
, , ,
start, , left,

21.4. <canvas>

693

end right.
<canvas> dir rtl (right-to-left ),
start
right, end left.

.21.12. textAlign textBaseline

textBaseline alphabetic,
Latin . ideographic
, .
hanging
( ).
top, middle bottom
, .
fillText() strokeText() .
.
, font

.
,
measureText(). TextMetrics,
font.
TextMetrics .
:
var width = c.measureText(text).width;

21.4.10.
stroke() fill() ( ).
clip(), .
,
. . 21.13 ,
.
,
.

694

21.

.21.13. ,

.21.13 polygon()
21.4 :
//
c.font = "bold 60pt sans-serif"; //
c.lineWidth = 2; //
c.strokeStyle = "#000"; //
//
c.strokeRect(175, 25, 50, 325); //
c.strokeText("<canvas>", 15, 330); // strokeText() fillText()
// , .
polygon(c,3,200,225,200); //
polygon(c,3,200,225,100,0,true); //
//
// .
c.clip();
// 5 , .
c.lineWidth = 10; // 10
//
c.stroke();
// ,
c.fillStyle = "#aaa" // -
c.fillRect(175, 25, 50, 325); //
c.fillStyle = "#888" // -
c.fillText("<canvas>", 15, 330); //

, clip()
,
. , clip()
. ,
, , clip()
save(),
restore().

21.4. <canvas>

695

21.4.11.
CanvasRenderingContext2D ,
.
, , ,
, .
.21.14 , ,
, .

.21.14.

shadowColor .
, ,
,
.
:
.
- .
shadowOffsetX shadowOffsetY X Y.
0,
, .
, ,
, ,
. ,
.
shadowBlur , .
0, ,
. ,
, .

.
21.8 ,
.21.14
, .
21.8.
//
c.shadowColor = "rgba(100,100,100,.4)"; //
c.shadowOffsetX = c.shadowOffsetY = 3; //

696

21.

c.shadowBlur = 5; //
//
c.lineWidth = 10;
c.strokeStyle = "blue";
c.strokeRect(100, 100, 300, 200); //
c.font = "Bold 36pt Helvetica";
c.fillText("Hello World", 115, 225); //
// .
// . ,
// .
c.shadowOffsetX = c.shadowOffsetY = 20;
c.shadowBlur = 10;
c.fillStyle = "red"; // ,
c.fillRect(50,25,200,65); //

shadowOffsetX shadowOffsetY
rotate() scale().
, , 90 ,
,
. ,
, ,
. ,
, .1

21.4.12.
(, ),
Canvas . drawImage()
(
),
, .
drawImage() , .
.
<img> Image,
Image().
<canvas> <video>.
drawImage() <img> <video>,
, .
draw
Image() X Y ,
.
. X Y
,
.
drawImage()
X Y, , .
1

5 Google Chrome
, .

21.4. <canvas>

697

.
(x,y),
(x+width, y+height). .
.
,
,
.
drawImage()
,
.

. CSS.
<canvas>,

, ,
.
( ) ,
.
21.9 drawImage().
,
, , .
.21.15, ,
,
.

.21.15. drawImage()
21.9. drawImage()
//
c.moveTo(5,5);
c.lineTo(45,45);
c.lineWidth = 8;
c.lineCap = "round";
c.stroke();
//
c.translate(50,100);
c.rotate(-45*Math.PI/180); //
c.scale(10,10); // ,
// drawImage
c.drawImage(c.canvas,
0, 0, 50, 50, // :
0, 0, 50, 50); // :

698

21.

,
toDa
taURL(). , , toDataURL()
Canvas, CanvasRenderingContext2D.
toDataURL() PNG, URL data:.
URL <img>,
, :
var img = document.createElement("img"); // <img>
img.src = canvas.toDataURL(); // src
document.body.appendChild(img); //

PNG .
,
MIME-
toDataURL(). .
, , , toDataURL().
, toDataURL() <canvas>,
. ,
, (,
drawImage(), , CanvasPattern),
, , <canvas>.

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

, ,
, .
. ,
, ,
, .
, ( )
, drawImage(). ,
, ,
. ,
. ,
.
: ,
, .
globalCompositeOperation.
source-over,

21.4. <canvas>

699

(over)
, .
copy, :
.
globalCompositeOperation
destination-over.
,
.
, .
source-over, destination-over copy
, Canvas
11 globalCompositeOperation.
, ,
,
, , .
.21.16 11
:
. 11
, .
globalCompositeOperation , .

.21.16.

. 21.17 ,
.
,
.
,
, ,
. ,
CanvasRenderingContext2D

700

21.

,
11 .

.21.17.


5 11 : copy, source-in, sourceout, destination-atop destination-in -
.
,
, .
, ,
,
, .
.
Safari Chrome :
, fill(), stroke()
. IE9, , . Firefox Opera
:
.
, ,
. Firefox Opera ,
, ,
, . .21.16
.21.17 Firefox. , ,
copy, source-in, sourceout, destination-atop destination-in, ,
: , ,
,
( lineWidth), . .21.18
, .21.17, Chrome.

21.4. <canvas>

701

.21.18.

HTML5
, Firefox Opera.

. ,
.
, , , Safari Chrome,
,
.
, .
drawImage(),

. , Firefox,
,
, ,
,
.

21.4.14.
getImageData() ImageData,
( R, G, B A) .
ImageData createImageData().
ImageData ,
putImageData().

. , getImageData(),
: CSS-
. putImageData()
. , put
ImageData() .
, globalAlpha .

702

21.


. 21.10 ,
<canvas>.
getImageData() putImageData()
, ImageData
, . getIma
geData() putImageData() CanvasRenderingContext2D,
ImageData .
21.10.
ImageData
// "" ,
// . n 2.
// , .
// .
function smear(c, n, x, y, w, h) {
// ImageData,
var pixels = c.getImageData(x,y,w,h);
// ,
// ImageData.
// ImageData
// . ,
// ImageData :
// var output_pixels = c.createImageData(pixels);
// w h:
// CSS- .
var width = pixels.width, height = pixels.height;
// , , .
// 4 , R,G,B,A.
var data = pixels.data;
// ,
// 1/n- m/n-
var m = n-1;
for(var row = 0; row < height; row++) { //
var i = row*width*4 + 4; //
for(var col = 1; col < width; col++, i += 4) { //
data[i] = (data[i] + data[i-4]*m)/n; //
data[i+1] = (data[i+1] + data[i-3]*m)/n; //
data[i+2] = (data[i+2] + data[i-2]*m)/n; //
data[i+3] = (data[i+3] + data[i-1]*m)/n; // -
}
}
//
c.putImageData(pixels, x, y);
}

, getImageData()
, toDataURL():
, (,
drawImage(), , CanvasPattern),
, , <canvas>.

21.4. <canvas>

703

21.4.15.
isPointInPath() ,
( ) , true, , false
.
.
: ,
, .
clientX clientY MouseEvent
isPointInPath(). -,
Window
<canvas>. -,
,
. 21.11 ,
MouseEvent .
21.11.
// true,
// CanvasRenderingContext2D.
function hitpath(context, event) {
// <canvas>
var canvas = context.canvas;
//
var bb = canvas.getBoundingClientRect();
//
var x = (event.clientX-bb.left)*(canvas.width/bb.width);
var y = (event.clientY-bb.top)*(canvas.height/bb.height);
// isPointInPath
return context.isPointInPath(x,y);
}

hitpath() ,
:
canvas.onclick = function(event) {
if (hitpath(this.getContext("2d"), event) {
alert(" !"); //
}
};

getImageData()
, . (
) ,
,
- . 21.12 ,
.
21.12.
// true, ,
// .
function hitpaint(context, event) {

704

21.

//
var canvas = context.canvas;
var bb = canvas.getBoundingClientRect();
var x = (event.clientX-bb.left)*(canvas.width/bb.width);
var y = (event.clientY-bb.top)*(canvas.height/bb.height);
// ( , CSS-
// )
var pixels = c.getImageData(x,y,1,1);
// -,
// true ()
for(var i = 3; i < pixels.data.length; i+=4) {
if (pixels.data[i] !== 0) return true;
}
// .
return false;
}

21.4.16. <canvas>:

.
(sparkline) (
) , :
. sparkline
(Edward Tufte), :
,
, , .
, ,
. (
. Beautiful Evidence [Graphics Press].)
21.13 JavaScript,
- .
. ,
onLoad() 13.5.
21.13. <canvas>
/*
* CSS- "sparkline",
* .
*
* :
* <span class="sparkline">3 5 7 6 6 9 11 15</span>
*
* CSS :
* .sparkline { background-color: #ddd; color: red; }
*
* - CSS- color .
* - , .
* - data-height, ,
* font-size .
* - data-width, ,

21.4. <canvas>

705

* , data-dx,
* , , , 6
* - y
* data-ymin data-ymax, ,
* .
*/
onLoad(function() { //
// "sparkline"
var elts = document.getElementsByClassName("sparkline");
main: for(var e = 0; e < elts.length; e++) { //
var elt = elts[e];
// .
// , .
var content = elt.textContent || elt.innerText; //
var content = content.replace(/^\s+|\s+$/g, ""); //
var text = content.replace(/#.*$/gm, ""); //
text = text.replace(/[\n\r\t\v\f]/g, " ");// . \n .
var data = text.split(/\s+|\s*,\s*/); //
for(var i = 0; i < data.length; i++) { //
data[i] = Number(data[i]); //
if (isNaN(data[i])) continue main; //
}
// , , y
// , data- .
var style = getComputedStyle(elt, null);
var color = style.color;
var height = parseInt(elt.getAttribute("data-height")) ||
parseInt(style.fontSize) || 20;
var width = parseInt(elt.getAttribute("data-width")) ||
data.length * (parseInt(elt.getAttribute("data-dx")) || height/6);
var ymin = parseInt(elt.getAttribute("data-ymin")) || Math.min.apply(Math, data);
var ymax = parseInt(elt.getAttribute("data-ymax")) || Math.max.apply(Math, data);
if (ymin >= ymax) ymax = ymin + 1;
// <canvas>.
var canvas = document.createElement("canvas");
canvas.width = width; //
canvas.height = height;
canvas.title = content; //
elt.innerHTML = ""; //
elt.appendChild(canvas); //
// (i,data[i]), .
var context = canvas.getContext('2d');
for(var i = 0; i < data.length; i++) { //
var x = width*i/data.length; // i
var y = (ymax-data[i])*height/(ymax-ymin); // data[i]
context.lineTo(x,y); // lineTo() moveTo()
}
context.strokeStyle = color; //
context.stroke(); //
}
});

22
22.

HTML5

HTML5
HTML,
-,
HTML .
Open Web Platform.
HTML5,
.
HTML5:
15 getElementsByClassName(), querySe
lector
All() .
16 classList .
18 XMLHttpRequest Level2,
HTTP- Event
Source, Server-Sent Events.
20 Web Storage
-.
21 <audio>, <video> <canvas>,
SVG.
HTML5:
22.1 Geolocation,

( ).
22.2
, -
Back (
) Forward () ,
-.
22.3
.

22.1.

707

(
13.6.2),
, -.
22.4 HTML5:
JavaScript
.
22.5
, .
22.6 (Blob):
, ,

.
, ,
: File FileReader, BlobBuilder URL- blob://.
22.7 ,
-
.
, .
22.8 IndexedDB,

. , IndexedDB
.
, 22.9 - Web So
ckets, - -

/,
XMLHttpRequest.

, ,
, ,
,
.
, ,

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

22.1.
Geolocation (http://www.w3.org/TR/geolocation-API/)
JavaScript
.
, ,
. , ,
, ,

708

22. HTML5

Geolocation, ,
JavaScript-
.
Geolocation navigator.
geolocation. :
navigator.geolocation.getCurrentPosition()
.
navigator.geolocation.watchPosition()
,
,
.
navigator.geolocation.clearWatch()
.
,
watchPosition().
, GPS,

GPS.
. IP- -,
(
), (
,
).
,
.
-,
( ).

, ,
Geolocation :
getCurrentPosition() watchPosition() ,
, ,
( ).
:
navigator.geolocation.getCurrentPosition(function(pos) {
var latitude = pos.coords.latitude;
var longitude = pos.coords.longitude;
alert(" : " + latitude + ", " + longitude);
});


(),
. 22.1
: getCurrentPosition(),
, (
Google Maps) ,
.

22.1.

709

22.1.

// <img>, (
// ) .
// ,
// , . ,
// .
function getmap() {
// geolocation
if (!navigator.geolocation)
throw " ";
// <img>, ,
// img .
var image = document.createElement("img");
navigator.geolocation.getCurrentPosition(setMapURL);
return image;
// ,
// , .
function setMapURL(pos) {
//
var latitude = pos.coords.latitude; //
var longitude = pos.coords.longitude; //
var accuracy = pos.coords.accuracy; //
// URL
// Google Map
var url = "http://maps.google.com/maps/api/staticmap" +
"?center=" + latitude + "," + longitude +
"&size=640x640&sensor=true";
// ,
var zoomlevel=20; //
if (accuracy > 80) //
zoomlevel -= Math.round(Math.log(accuracy/50)/Math.LN2);
url += "&zoom=" + zoomlevel; // URL
// . , Google!
image.src = url;
}
}

Geolocation ,
22.1:
get
CurrentPosition() watchPosition()
, .


. :
,

.

710

22. HTML5

, ( )
, ,
.
22.2.
22.2.
// .
function whereami(elt) {
// getCurrentPosition() 3
var options = {
// (, GPS),
// true. , ,
// .
enableHighAccuracy: false, // :
// , .
// 0,
// .
maximumAge: 300000, // , 5
// .
// Infinity,
// getCurrentPosition()
timeout: 15000 // 15
};
if (navigator.geolocation) // ,
navigator.geolocation.getCurrentPosition(success, error, options);
else
elt.innerHTML = " " +
" ";
//
function error(e) {
// . :
// 1:
// 2:
// 3:
elt.innerHTML = " " +
e.code + ": " + e.message;
}
//
function success(pos) {
// . , timestamp
// pos, coords.
var msg = "At " +
new Date(pos.timestamp).toLocaleString() + " " +
pos.coords.accuracy + " " +
pos.coords.latitude + " " +
pos.coords.longitude + " .";
// , .
if (pos.coords.altitude) {

22.2.

711

msg += " " + pos.coords.altitude + " " +


pos.coords.altitudeAccuracy + " .";
}
// ,
// .
if (pos.coords.speed) {
msg += " " +
pos.coords.speed + "/ " +
pos.coords.heading + ".";
}
elt.innerHTML = msg; //
}
}

22.2.
- , ,
Back Forward,
. ,

. -

.
,
Back Forward
. HTML5
.

location.hash hashchange.
:
, HTML5.
( IE) location.
hash URL, ,
. hash
URL
. location.hash
:
. ,
.
location.hash,
Back Forward
. ,
,
, ,
. HTML5,
hashchange
Window. , hashchange,
window.onhashchange ,

712

22. HTML5

,
. -
location.hash
, .
HTML5 ,
,
history.pushState() popstate. history.pushState(),
. ,
,
. ,
JSON.stringify(),
, Date RegExp ( ).
( ),

(, Back).
URL, .
URL-
URL,
, #state.
URL-
, URL
,
.


, pushState()
. ,
:
. HTML5
.
JSON.stringify()
JSON.parse() (6.9). JSON
JavaScript, .
HTML5 ,
Date RegExp,
ImageData ( <canvas> 21.4.14) FileList,
File Blob ( 22.6). JavaScript
,
,
, , , ..

,
, HTML5,
.

22.2.

713

pushState() History replaceState(),


,
, .
Back
Forward, popstate Window. ,
, state, (
) ,
pushState().
22.3 - ,
.22.1,
, HTML5,
, .
, Firefox4
History,
. -, Firefox4
state History, ,
popstate. -,
Firefox4 popstate ,
. ,
, , , Firefox4.

.22.1.
x22.3. pushState()
<!DOCTYPE html>
<html><head><title>I'm thinking of a number...</title>
<script>
window.onload = newgame; //
window.onpopstate = popState; //
var state, ui; // , newgame()
function newgame(playagain) { // " "
//
ui = {

714

22. HTML5

heading: null, // <h1> .


prompt: null, // .
input: null, // , .
low: null, //
mid: null, // ..., .
high: null
};
// id
for(var id in ui) ui[id] = document.getElementById(id);
//
ui.input.onchange = handleGuess;
//
state = {
n: Math.floor(99 * Math.random()) + 1, // : 0 < n < 100
low: 0, // ,
high: 100, // ,
guessnum: 0, //
guess: undefined // ,
};
// ,
display(state);
//
//
//
//
//
//
//
//
//
//
//
//
//
//
if
}

onload,
Play Again ( ), .
playagain true, ,
.
"load", , "load"
-
.
,
. , pushState(), "load"
"popstate". ,
, "popstate".
, . , "popstate"
state null, , ,
replaceState .
(playagain === true) save(state);

// pushState(),
function save(state) {
if (!history.pushState) return;// , pushState()
// URL-.
// , ,
// .
// URL-,
// .
var url = "#guess" + state.guessnum;
// URL
history.pushState(state, //
"", // :
url); // URL :
}

22.2.
// onpopstate, .
function popState(event) {
if (event.state) { // ,
// , event.state
// , ,
// .
state = event.state; //
display(state); //
}
else {
// , "popstate"
// . null
// : newgame().
// display() .
history.replaceState(state, "", "#guess" + state.guessnum);
}
};
// , .
// , .
function handleGuess() {
//
var g = parseInt(this.value);
//
if ((g > state.low) && (g < state.high)) {
//
if (g < state.n) state.low = g;
else if (g > state.n) state.high = g;
state.guess = g;
state.guessnum++;
//
save(state);
//
display(state);
}
else { // :
alert("Please enter a number greater than " + state.low +
" and less than " + state.high);
}
}
// , .
function display(state) {
//
ui.heading.innerHTML = document.title =
"I'm thinking of a number between " +
state.low + " and " + state.high + ".";
//
ui.low.style.width = state.low + "%";
ui.mid.style.width = (state.high-state.low) + "%";
ui.high.style.width = (100-state.high) + "%";
// ,
ui.input.style.visibility = "visible";
ui.input.value = "";
ui.input.focus();

715

716

22. HTML5

// ,
if (state.guess === undefined)
ui.prompt.innerHTML = "Type your guess and hit Enter: ";
else if (state.guess < state.n)
ui.prompt.innerHTML = state.guess + " is too low. Guess again: ";
else if (state.guess > state.n)
ui.prompt.innerHTML = state.guess + " is too high. Guess again: ";
else {
// ,
// Play Again ( ).
ui.input.style.visibility = "hidden"; //
ui.heading.innerHTML = document.title = state.guess + " is correct! ";
ui.prompt.innerHTML =
"You Win! <button onclick='newgame(true)'>Play Again</button>";
}
}
</script>
<style> /* CSS-, */
#prompt { font-size: 16pt; }
table { width: 90%; margin:10px; margin-left:5%; }
#low, #high { background-color: lightgray; height: 1em; }
#mid { background-color: green; }
</style>
</head>
<body><!-- -->
<!-- -->
<h1 id="heading">I'm thinking of a number...</h1>
<!-- , -->
<table><tr><td id="low"></td><td id="mid"></td><td id="high"></td></tr></table>
<!-- -->
<label id="prompt"></label><input id="input" type="text">
</body></html>

22.3.

14.8,
, , ,
. ,
,
.
, -,

.
Window,
, , -
( )
.
.
,
, postMessage(),

22.3.

717


.
HTML5 (
IE8 ).
, ,
Window, , ,
.
postMessage() .
. HTML5,
, (
), ( Firefox4
beta) , ,
,
JSON.stringify() (6.9).
,
, .
, () ( URL-,
, , ).
:
,
, postMessage()
, ,
.

, "*",
. ,
, , "/".
,
postMessage() message Win
dow.
message, :
data
, postMessage() .
source
Window, .
origin
, ( URL) ,
.
onmessage()
origin
.

postMessage() message , ,
- , ,
. ,
<iframe>. , ,

718

22. HTML5

, -
- .
<script>,
JavaScript, , ,
.
( -),
, .

: HTML-,
message
JavaScript. -, ,
, postMessage().
22.4 22.5. 22.4
, <iframe>,
Twitter ,
. ,
.
22.4. Twitter postMessage()
<!DOCTYPE html>
<!- Twitter.
<iframe> ,
postMessage(). <iframe>,
<script>, .
-->
<html>
<head>
<style>body { font: 9pt sans-serif; }</style>
<!-- jQuery jQuery.getJSON() -->
<script src="http://code.jquery.com/jquery-1.4.4.min.js"/></script>
<script>
// window.onmessage,
// ( Firefox3) ,
// .
if (window.addEventListener)
window.addEventListener("message", handleMessage, false);
else
window.attachEvent("onmessage", handleMessage); // IE8
function handleMessage(e) {
// , :
// Twitter .
// , .
if (e.source !== window.parent) return;
var searchterm = e.data; // ,
// Ajax jQuery
// Twitter , .
jQuery.getJSON("http://search.twitter.com/search.json?callback=?",
{ q: searchterm },
function(data) { //

22.3.

719

var tweets = data.results;


// HTML-
var escaped = searchterm.replace("<", "&lt;");
var html = "<h2>" + escaped + "</h2>";
if (tweets.length == 0) {
html += "No tweets found";
}
else {
html += "<dl>"; // <dl> list of results
for(var i = 0; i < tweets.length; i++) {
var tweet = tweets[i];
var text = tweet.text;
var from = tweet.from_user;
var tweeturl = "http://twitter.com/#!/" +
from + "/status/" + tweet.id_str;
html += "<dt><a target='_blank' href='" +
tweeturl + "'>" + tweet.from_user +
"</a></dt><dd>" + tweet.text + "</dd>";
}
html += "</dl>";
}
// <iframe>
document.body.innerHTML = html;
});
}
$(function() {
// , .
// ,
// .
// onload, ,
// . ,
// ,
// onload. ,
// *, .
window.parent.postMessage("Twitter Search v0.1", "*");
});
</script>
</head>
<body>
</body>
</html>

22.5 JavaScript,
-,
Twitter.
,
postMessage() ,
URL . ,
- , .
22.5. Twitter
postMessage()
// JS Twitter Search Gadget
// ,

720

22. HTML5

// URL- .
// , , .
window.addEventListener("load", function() { // IE < 9
var origin = "http://davidflanagan.com"; //
var gadget = "/demos/TwitterSearch.html"; //
var iframe = document.createElement("iframe"); // iframe
iframe.src = origin + gadget; // URL
iframe.width = "250"; // 250
iframe.height = "100%"; //
iframe.style.cssFloat = "right"; //
//
document.body.insertBefore(iframe, document.body.firstChild);
//
var links = document.getElementsByTagName("a");
for(var i = 0; i < links.length; i++) {
// addEventListener IE8
links[i].addEventListener("mouseover", function() {
// url ,
// davidflanagan.com
iframe.contentWindow.postMessage(this.href, origin);
}, false);
}
}, false);

22.4.
JavaScript
, :
, ,
, , .

, , ,

. , JavaScript
,
- .
Ajax ,
JavaScript
load() require() JavaScript.
Web Workers1
JavaScript.
, ,
.
, Window Document
1

Web Workers HTML5,


, , ,
.
http://dev.w3.org/html5/workers/ http://whatwg.org/ww.

22.4.

721


. , DOM -
, ,
,
,
.
, ,
,
. -

, ,
.
,
Web Workers .
Worker, ,
. WorkerGlobalScope,
,
. .
.

22.4.1. Worker
,
Worker(), URL-, Ja
vaScript, :
var loader = new Worker("utils/loader.js");

URL-,
URL- , ,
Worker(). URL-,
(, ), .
Worker
postMessage(). , postMessage(),
( ),
message:
loader.postMessage("file.txt");

, , postMessage() Window,
postMessage() Worker ,
, (22.3). , postMessage()
Worker ,
Window.postMessage(),
.

message Worker:
worker.onmessage = function(e) {
var message = e.data; //
console.log(": " + message); //
}

722

22. HTML5

,
, :
worker.onerror = function(e) {
// ,
console.log(" " + e.filename + ":" + e.lineno + ": " + e.message);
}

, , Worker
addEventListener() removeEventListener(),
onmessage onerror,
.
Worker , terminate(),
.

22.4.2.
Worker()
URL- JavaScript.
, JavaScript,
, .
WorkerGlobalScope.
WorkerGlobalScope , Java
Script, , Window.
WorkerGlobalScope postMessage()
onmessage, Worker,
. postMessage()
message , , ,
onmessage.
: , WorkerGlobalScope
, postMessage() onmessage
, ,
.
close() ,
terminate() Worker. , ,
Worker , ,
, onclose.
postMessage() ,
,
. ,
close(),
, .
importScripts(),
WorkerGlobalScope:
. :
//
importScripts("collections/Set.js", "collections/Map.js", "utils/base64.js");

importScripts() URL-,

22.4.

723

JavaScript. URL- URL-


, Worker().
, .
- ,
. ,
importScripts(), importScripts(),
. , , import
Scripts() ,
.
importScripts() : ,
. ,
importScripts(), ,
:
.
JavaScript, ,
. :
,
,
.
WorkerGlobalScope
, Java
Script, JSON, isNaN() Date(). (
Global, .) ,
, WorkerGlobalScope
Window:
self . , , Wor
kerGlobalScope window,
Window.


(
) , ,
, .
onmessage,
, message.
, ,
( )
, .

,
.
onmessage, XMLHttpRequest.
onload
setTimeout(),
. .

724

22. HTML5

setTimeout(), clearTimeout(), setInterval() clear

Interval().
location, URL-, Worker().

Location,
location Window. Location href, protocol, host, host
name, port, pathname, search hash.
.
navigator, , ,
Navigator . navigator
appName, appVersion, platform, userAgent onLine.
, : addEvent
Listener() removeEventListener().
onerror, ,
Window.onerror, 14.6.
, ,
, URL- . false,
,
error Worker. (
.)

Worker
, ,
: ( )
. Web Workers
,
.
. ,
,
.

.
Messa
gePort. ,
,

. MessagePort postMessage()
onmessage . HTML5
MessagePort
MessageChannel(). MessagePort
( postMessage())

. MessagePort MessageChannel
,
.

22.4.

725

, WorkerGlobalScope ,
. XMLHttpRequest(),
HTTP- ( 18), Worker(),
. (
Worker()
Chrome Safari.)
HTML5, ,
, Window,
WorkerGlobalScope.
Window WorkerGlobalScope.

.

22.4.3.

. ,
,
, .
,
.
22.6 smear(), <img>
.
. 21
<canvas>
ImageData.
<img> <canvas>
postMessage(), ImageData (
). 22.6 Worker
postMessage(), .
,
<canvas>, URL-
data:// URL- src
<img>.
22.6.
// .
// : <img src="testimage.jpg" onclick="smear(this)"/>
function smear(img) {
// <canvas> ,
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
//
var context = canvas.getContext("2d");
context.drawImage(img, 0, 0);
var pixels = context.getImageData(0,0,img.width,img.height)
//
var worker = new Worker("SmearWorker.js"); //

726

22. HTML5

worker.postMessage(pixels); //
//
worker.onmessage = function(e) {
var smeared_pixels = e.data; // ,
context.putImageData(smeared_pixels, 0, 0); //
img.src = canvas.toDataURL(); //
worker.terminate(); //
canvas.width = canvas.height = 0; //
}
}

22.7 ,
22.6.
: 21.10. ,

: onmessage
.
22.7.
// ImageData ,
//
onmessage = function(e) { postMessage(smear(e.data)); }
// ImageData , .
//
// , ,
// .
function smear(pixels) {
var data = pixels.data, width = pixels.width, height = pixels.height;
var n = 10, m = n-1; // n,
for(var row = 0; row < height; row++) { //
var i = row*width*4 + 4; // 2-
for(var col = 1; col < width; col++, i += 4) { //
data[i] = (data[i] + data[i-4]*m)/n; //
data[i+1] = (data[i+1] + data[i-3]*m)/n; //
data[i+2] = (data[i+2] + data[i-2]*m)/n; //
data[i+3] = (data[i+3] + data[i-1]*m)/n; // -
}
}
return pixels;
}

, 22.7
, .
22.6 Worker
. ,
,
terminate().
,

JavaScript. 18.1.2.1 ,
XMLHttpRequest HTTP-,

22.4.

727

,
.
, 22.8
, .
onmessage URL-,
XMLHttpRequest

. , - HTTP-
, ,
onerror Worker.


, WorkerGlobal
Scope ( , ),

console.log().
,
.
, error Worker.
-
, -
.
,
, . , 22.6

onmessage:
if (typeof e.data === "string") {
console.log("Worker: " + e.data);
return;
}


,
postMessage().

22.8. HTTP-
// Worker(),
//
// XMLHttpRequest.
// URL-.
// .
onmessage = function(e) {
var urls = e.data; // : URL-
var contents = []; // : URL-
for(var i = 0; i < urls.length; i++) {

728

22. HTML5

var url = urls[i]; // URL-


var xhr = new XMLHttpRequest(); // HTTP-
xhr.open("GET", url, false); // false .
xhr.send(); //
if (xhr.status !== 200) //
throw Error(xhr.status + " " + xhr.statusText + ": " + url);
contents.push(xhr.responseText); //
}
// URL-
postMessage(contents);
}

22.5.
7, JavaScript
length.
JavaScript-.
. Java
Script ,
JavaScript .
, (7.11),
:
. ,
, (
) () .
.
0
.
,
.
:

Int8Array()

Uint8Array()

Int16Array()

16-

Uint16Array()

16-

Int32Array()

32-

Uint32Array()

32-

Float32Array()

32-

Float64Array()

64-


. ,
.

729

22.5.

,
, :
var bytes = new Uint8Array(1024); //
for(var i = 0; i < bytes.length; i++) //
bytes[i] = i & 0xFF; //
var copy = new Uint8Array(bytes); //
var ints = new Int32Array([0,1,2,3]); //



8

4

JavaScript
.
, ,
.
, .
, ,
, , .
,
Int8Array ,
JavaScript:
// n.
// " "
function sieve(n) {
var a = new Int8Array(n+1); // a[x] 1, x -
var max = Math.floor(Math.sqrt(n)); //
var p = 2; // 2 -
while(p <= max) { // max
for(var i = 2*p; i <= n; i += p) // , p,
a[i] = 1; //
while(a[++p]) /* */; // } //
while(a[n]) n--; // . .,
return n; //
}

sieve() , Int8Array()
Array(),
n.
:
var
var
var
var

matrix = new Float64Array(9); //


3dPoint = new Int16Array(3); //
rgba = new Uint8Array(4); //
sudoku = new Uint8Array(81); //

3x3
3-
4- RGBA
9x9

, JavaScript,

.
. set()
:
var bytes = new Uint8Array(1024) // 1K
var pattern = new Uint8Array([0,1,2,3]); // 4
bytes.set(pattern); //

730

22. HTML5

bytes.set(pattern, 4); //
bytes.set([0,1,2,3], 8); //

subarray(),
, :
var ints = new Int16Array([0,1,2,3,4,5,6,7,8,9]); // 10
var last3 = ints.subarray(ints.length-3, ints.length); // 3
last3[0] // => 7: , ints[7]

, subarray() .
:
ints[9] = -1; // ...
last3[2] // => -1:

, subarray()
, :
, ArrayBuffer.
,
:
last3.buffer // => ArrayBuffer
last3.buffer == ints.buffer // => true: -
last3.byteOffset // => 14: 14-
last3.byteLength // => 6: 6 (3 16- )

ArrayBuffer , :
last3.byteLength // => 6: 6
last3.buffer.byteLength // => 20: 20

, <canvas>
JavaScript

WebGL <canvas>,
WebGL. WebGL
,
, . 21 ,
Canvas getImageData(),
ImageData. data ImageData
. HTML CanvasPixelArray,
, , , Uint8Array,
, 0255.
, .
JavaScript, ,
, ,
, , ,
.

731

22.5.

ArrayBuffers .
, Array
Buffer . :
ArrayBuffer , Java
Script, :
var bytes = new Uint8Array(8); // 8
bytes[0] = 1; // 1
bytes.buffer[0] // => undefined: 0
bytes.buffer[1] = 255; //
bytes.buffer[1] // => 255: JavaScript-
bytes[1] // => 0:

ArrayBuffer ,
ArrayBuffer(), ArrayBuffer
:
var
var
var
var
var

buf = new ArrayBuffer(1024*1024); //


asbytes = new Uint8Array(buf); //
asints = new Int32Array(buf); //
lastK = new Uint8Array(buf,1023*1024); //
ints2 = new Int32Array(buf, 1024, 256); //



32-

2- 256


8, 16, 32 64 .
, .. ,
.
,
.
ArrayBuffer .

.
, , :
// 0x00000001
// 01 00 00 00, ,
// .
// 00 00 00 01.
var little_endian = new Int8Array(new Int32Array([1]).buffer)[0] === 1;


.
,
. 22.6 , ArrayBuffer
, .
, ,
,
. , ,
Int8Array Uint8Array,

.
DataView,
ArrayBuffer, :

732

22. HTML5

var data; // , ArrayBuffer


var view = DataView(data); //
var int = view.getInt32(0); // 32-
// , 0-
int = view.getInt32(4,false); // 32- ,
//
int = view.getInt32(8,true) // 4
//
view.setInt32(8,int,false); // ,
//

DataView get
. , getInt16(), getUint32() get
Float64().
ArrayBuffer. , getInt8() getUint8(),
.
false,
. true,
.
DataView set,
ArrayBuffer.
. .
, setInt8() setUint8(),
. false,
,
. true,
, .

22.6.
(Blob) , ,
. Blob SQL,
Binary Large Object ( ). JavaScript
,
, : Blob
.
, .. : ,
, , MIME-
:
var blob = ... // ,
blob.size //
blob.type // MIME- "",
var subblob = blob.slice(0,1024, "text/plain"); //
var last = blob.slice(blob.size-1024, 1024); // -
//

- ,
(
), ,
,
slice().

733

22.6.

,
(
).
,

JavaScript, . .22.2
,
, ,

. ,
, URL-.
, .
,
,
, :

( ), ,

message ( 22.3 22.4).

XM

LH

XM

LH

ttp

Re

ttp

Re

qu

qu

es

t.r

es

t.s

es

en

po

d()

ns

d()

en

)
er(

uff
yB

rra

pp

r.a

sA

dA

de

uil

bB

Blo

rea
er.

me

ad

stM

e
sag

BlobBuilder.append()

e
eR

g
ssa

Fil

e()

po

File
ter
Wri
File

FileReader.readAsText()

IndexedDB API

FileReader.readAsDataURL()

URL.createObjectURL()

URL

A
,

.22.2. ,

734

22. HTML5

22.8.
HTTP,

, XHR2.
22.6.2.
,
BlobBuilder , ArrayBuffer (22.5)
. BlobBuilder 22.6.3.
, , , , File JavaScript
Blob: File
, . File
<input type="file">
(drag-and-drop), 22.6.1. File

, 22.7.
, ,
, :

postMessage() ( 22.3 22.4).
(
22.8).
, send()
XMLHttpRequest. , 18.9
(, File
Blob).
createObjectURL(),
URL- blob://, ,
DOM CSS.
22.6.4.
FileReader, (
, )
ArrayBuffer. 22.6.5.

FileWriter, 22.7,
.

. ,
,
, .

22.6.1.
<input type="file">
HTML-.
,
, .

22.6.

735

value ,
,
.
,
. ,

, .
, , files
<input type="file"> FileList. ,
, File,
, . File Blob,
name lastModifiedDate:
<script>
//
function fileinfo(files) {
for(var i = 0; i < files.length; i++) { // files -
var f = files[i];
console.log(f.name, // :
f.size, f.type, // - Blob
f.lastModifiedDate); // File
}
}
</script>
<!-- fileinfo()-->
<input type="file" accept="image/*" multiple onchange="fileinfo(this.files)"/>

,
. 22.6.4 22.6.5 ,
.
, <input>,
,
. drop,
dataTransfer.files FileList,
, .
17.7,
22.10.

22.6.2.
18 HTTP- XML
HttpRequest ,
XMLHttpRequest Level2 (XHR2).
XHR2 URL ,
. ,
,
XHR2 .
22.9 .
18.2, URL-
.

736

22. HTML5

22.9. XMLHttpRequest
// GET URL
// . :
// , , .
function getBlob(url, callback) {
var xhr = new XMLHttpRequest(); // XHR
xhr.open("GET", url); // URL-
xhr.responseType = "blob" //
xhr.onload = function() { // onload , onreadystatechange
callback(xhr.response); //
} // : .response, .responseText
xhr.send(null); //
}


,
onprogress ,
22.6.5.

22.6.3.

, , URL- . ,
-, ,
. Blob
BlobBuilder:
// BlobBuilder
var bb = new BlobBuilder();
// NUL
bb.append(" 10 " +
"32- .");
bb.append("\0"); // NUL,
// ArrayBuffer
var ab = new ArrayBuffer(4*10);
var dv = new DataView(ab);
for(var i = 0; i < 10; i++) dv.setInt32(i*4,i);
// ArrayBuffer
bb.append(ab);
// , MIME-
var blob = bb.getBlob("x-optional/mime-type-here");

, slice(),
.
, append() BlobBuilder.

22.6.4. URL-,
,
. ,
. ,
, URL-, . URL-

22.6.

737

, URL-:
DOM, XMLHttpRequest.
URL-, ,
createObjectURL(). Fire
fox4 URL, Chrome
Webkit , webkitURL.
( )
Window.
URL-, ,
, :
var getBlobURL = (window.URL && URL.createObjectURL.bind(URL)) ||
(window.webkitURL && webkitURL.createObjectURL.bind(webkitURL)) ||
window.createObjectURL;


, URL ( webkitURL).
createObjectURL(), URL-
( ). blob://,
,
. , URL-
URL- data://,
. URL-, ,
Blob, . URL-
blob:// URL- file://,
,
,
.
22.10 . -,
,
(drag-and-drop), . -,
, create
ObjectURL() URL- <img>,
, URL-.
22.10. URL-

<!DOCTYPE html>
<html><head>
<script>
// Firefox Webkit
// createObjectURL()
var getBlobURL = (window.URL && URL.createObjectURL.bind(URL)) ||
(window.webkitURL && webkitURL.createObjectURL.bind(webkitURL)) ||
window.createObjectURL;
var revokeBlobURL = (window.URL && URL.revokeObjectURL.bind(URL)) ||
(window.webkitURL && webkitURL.revokeObjectURL.bind(webkitURL)) ||
window.revokeObjectURL;
// droptarget,
//
window.onload = function() {

738

22. HTML5

// , .
var droptarget = document.getElementById("droptarget");
// droptarget ,
// .
droptarget.ondragenter = function(e) {
// , - , .
// dropzone,
// HTML5, .
var types = e.dataTransfer.types;
if (!types ||
(types.contains && types.contains("Files")) ||
(types.indexOf && types.indexOf("Files") != -1)) {
droptarget.classList.add("active"); // droptarget
return false; //
} //
};
// ,
//
droptarget.ondragleave = function() {
droptarget.classList.remove("active");
};
//
droptarget.ondragover = function(e) { return false; };
// , URL-
// .
droptarget.ondrop = function(e) {
var files = e.dataTransfer.files; //
for(var i = 0; i < files.length; i++) { //
var type = files[i].type;
if (type.substring(0,6) !== "image/") //
continue; //
var img = document.createElement("img"); // <img>
img.src = getBlobURL(files[i]); // URL blob:// <img>
img.onload = function() { // .
this.width = 100; //
document.body.appendChild(this); // .
revokeBlobURL(this.src); // !
}
}
droptarget.classList.remove("active"); //
return false; //
}
};
</script>
<style> /* */
#droptarget { border: solid black 2px; width: 200px; height: 200px; }
#droptarget.active { border: solid red 4px; }
</style>
</head>
<body> <!-- -->
<div id="droptarget"> </div>
</body>
</html>

22.6.

739

URL- (13.6.2),
, .
URL- file://, , -
-. URL-
. ,
, postMessage() URL-
, , URL-
.
URL- . URL-
,
, URL-. , ,
URL-
, -.
URL-
URL.revokeObjectURL() ( webkitURL.revokeObject
URL()), , , 22.10 .
.
,
. -
URL- ,
,
. JavaScript ,
URL- - , ,
. ,
, URL-
. 22.10 , ,
,
, BlobBuilder
XMLHttpRequest .
URL- blob:// http://,
URL- blob://
HTTP-. URL-
404 Not Found.
URL-
403 Not Allowed. URL-
GET,
200 OK Content-Type
type Blob. URL-
URL- http://,
XMLHttpRequest. (,
,
FileReader.)

22.6.5.
,
,
URL- . FileReader

740

22. HTML5

, ,
BlobBuilder. (
BlobReader, ,
.)
,
, , XMLHttpRequest.

FileReaderSync, .
FileReader,
FileReader().
. load error
progress.
onload, onerror onprogress addEventListener().
, FileReader loadstart, loadend abort,
XMLHttpRequest (
18.1.4).
FileReader
,
, : readAsText(), readAsArrayBuffer(), readAsDataURL()
readAsBinaryString(). (,

JavaScript, 22.4,
,
.)
, .
Blob . readAsText()
,
. ,
ASCII UTF-8 ( UTF-16
(byte-order mark, BOM)).
FileReader
readyState.
0, , .
- , 1
2. result
ArrayBuffer. -
readyState result
onprogress onload.
22.11 , readAsText()
, .
22.11. FileReader
<script>
// <pre>
function readfile(f) {
var reader = new FileReader(); // FileReader
reader.readAsText(f); //
reader.onload = function() { //

22.6.

741

var text = reader.result; //


var out = document.getElementById("output"); // output
out.innerHTML = ""; //
out.appendChild(document.createTextNode(text));//
} //
reader.onerror = function(e) { // -
console.log("Error", e); //
};
}
</script>
// :
<input type="file" onchange="readfile(this.files[0])"></input>
<pre id="output"></pre>

readAsArrayBuffer() readAsText(), ,
,
ArrayBuffer . 22.12
readAsArrayBuffer()
.
22.12.
<script>
// 4 . "",
// , .
function typefile(file) {
var slice = file.slice(0,4); // 4
var reader = new FileReader(); // FileReader
reader.readAsArrayBuffer(slice); //
reader.onload = function(e) {
var buffer = reader.result; // - ArrayBuffer
var view = new DataView(buffer); //
var magic = view.getUint32(0, false); // 4 ,
switch(magic) { //
case 0x89504E47: file.verified_type = "image/png"; break;
case 0x47494638: file.verified_type = "image/gif"; break;
case 0x25504446: file.verified_type = "application/pdf"; break;
case 0x504b0304: file.verified_type = "application/zip"; break;
}
console.log(file.name, file.verified_type);
};
}
</script>
<input type="file" onchange="typefile(this.files[0])"></input>

FileReader
FileReaderSync.
readAsText() readAsArrayBuffer(), ,
. ,

ArrayBuffer,
. 22.14
FileReaderSync.

742

22. HTML5

22.7.
22.6.5 FileReader,
, ,
. File Blob ,
File API. , , File API,
- ,
, , ,
..
Google Chrome.
, ,
,
, . ,
,
.
, .

. , ,
.
:
// . ,
// .
// .
var fs = requestFileSystemSync(PERSISTENT, 1024*1024);
//
//
requestFileSystem(TEMPORARY, //
50*1024*1024, // : 50
function(fs) { //
// fs
},
function(e) { //
console.log(e); // -
});

, ,
.
, PERSISTENT (
), -,
. ,
. ,
TEMPORARY (), -
, ,
, - .

, .
, .

. - (,

22.7.

743

) .


. , -
: -
-
.
, request
(). ,
,
.1
request ,
.
, ,
, root, .
DirectoryEntry, ,
DirectoryEntry.
, FileEntry. Directo
ryEntry DirectoryEntry FileEntry
( ,
). DirectoryEntry
createReader(), DirectoryReader,
.
FileEntry File (
Blob), . ,
FileReader ( 22.6.5).
FileEntry , FileWriter,
.

. ,
. , root ,
( ) FileEntry,
. FileEntry File
FileWriter .
:
// "hello.txt" .
//
// . .
requestFileSystem(PERSISTENT, 10*1024*1024, function(fs) { //
fs.root.getFile("hello.txt", {}, function(entry) { // FileEntry
entry.file(function(file) { // File
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function() { //
1

Chrome
, , --unlimitedquota-for-files.

744

22. HTML5

console.log(reader.result);
};
});
});
});

22.13 . ,
,
, .
22.13.

/*
* Google Chrome10.0 dev.
* Chrome :
* --unlimited-quota-for-files :
* --allow-file-access-from-files : URL file://
*/
// , ,
// .
// .
function logerr(e) { console.log(e); }
// requestFileSystem() ,
// .
// , .
var filesystem; // ,
// , .
requestFileSystem(PERSISTENT, // TEMPORARY
10*1024*1024, // 10
function(fs) { //
filesystem = fs; //
}, // .
logerr); //
// .
function readTextFile(path, callback) {
// getFile(), FileEntry
//
filesystem.root.getFile(path, {}, function(entry) {
// FileEntry, .
// FileEntry.file(), File
entry.file(function(file) { // File
var reader = new FileReader(); // FileReader
reader.readAsText(file); //
reader.onload = function() { //
callback(reader.result); // callback
}
reader.onerror = logerr; // readAsText()
}, logerr); // file()
},
logerr); // getFile()
}
// , ,

22.7.

745

// . callback .
function appendToFile(path, contents, callback) {
// filesystem.root - .
filesystem.root.getFile( // FileEntry
path, //
{create:true}, // ,
function(entry) { // ,
entry.createWriter( // FileWriter
function(writer) { //
// .
//
writer.seek(writer.length); //
// Blob. contents
// , Blob ArrayBuffer.
var bb = new BlobBuilder()
bb.append(contents);
var blob = bb.getBlob();
//
writer.write(blob);
writer.onerror = logerr; // write()
if (callback) // callback
writer.onwrite = callback; //
},
logerr); // createWriter()
},
logerr); // getFile()
}
// , callback .
function deleteFile(name, callback) {
filesystem.root.getFile(name, {}, // FileEntry
function(entry) { // FileEntry
entry.remove(callback, //
logerr); //
}, // remove()
logerr); // getFile()
}
//
function makeDirectory(name, callback) {
filesystem.root.getDirectory(name, //
{ //
create: true, // , .
exclusive:true // ,
},
callback, //
logerr); //
}
//
// callback
function listFiles(path, callback) {
// , .
//
// ( ).
if (!path) getFiles(filesystem.root);

746

22. HTML5

else filesystem.root.getDirectory(path, {}, getFiles, logerr);


function getFiles(dir) { //
var reader = dir.createReader(); //
var list = []; //
reader.readEntries(handleEntries, //
logerr); //


DirectoryReader


.

// .
// readEntries(),
// . ,
// callback.
function handleEntries(entries) {
if (entries.length == 0) callback(list); //
else {
//
// . , ,
// FileEntry, .
for(var i = 0; i < entries.length; i++) {
var name = entries[i].name; //
if (entries[i].isDirectory) name += "/"; //
list.push(name); //
}
//
reader.readEntries(handleEntries, logerr);
}
}
}
}


,
. 22.14
, 22.13,
, .
22.14.
// ,
// ,
var filesystem = requestFileSystemSync(PERSISTENT, 10*1024*1024);
function readTextFile(name) {
// File FileEntry DirectoryEntry
var file = filesystem.root.getFile(name).file();
// FileReader
return new FileReaderSync().readAsText(file);
}
function appendToFile(name, contents) {
// FileWriter FileEntry DirectoryEntry
var writer = filesystem.root.getFile(name, {create:true}).createWriter();
writer.seek(writer.length); //
var bb = new BlobBuilder() // Blob
bb.append(contents);
writer.write(bb.getBlob()); //
}

22.8.

747

function deleteFile(name) {
filesystem.root.getFile(name).remove();
}
function makeDirectory(name) {
filesystem.root.getDirectory(name, { create: true, exclusive:true });
}
function listFiles(path) {
var dir = filesystem.root;
if (path) dir = dir.getDirectory(path);
var lister = dir.createReader();
var list = [];
do {
var entries = lister.readEntries();
for(var i = 0; i < entries.length; i++) {
var name = entries[i].name;
if (entries[i].isDirectory) name += "/";
list.push(name);
}
} while(entries.length > 0);
return list;
}
// ,
onmessage = function(e) {
// :
// { function: "appendToFile", args: ["test", "testing, testing"]}
//
var f = self[e.data.function];
var result = f.apply(null, e.data.args);
postMessage(result);
};

22.8.
- HTML,
CSS JavaScript .
,
HTML5, .
,
,
JavaScript,
.
-, Web Sto
rage 20.1,
, /.
,
. Web SQL
Database ,
SQL-. Chrome, Safari
Opera. Firefox IE , ,
.

748

22. HTML5

, SQL, ,
,
-.

, IndexedDB.
(
), Firefox4 Chrome11 ,
,
IndexedDB.
IndexedDB , , ,
, SQL.
, , - /,
Web Storage.
- ,
IndexedDB : -
, .

IndexedDB. ,
. IndexedDB
.
, (
, ,
). ,
.
,
, .
, Date.
IndexedDB
, . ,
, ,
.
, . ,
, , .


. ,
. (
IndexedDB.)
.
, .

,
.

( ), IndexedDB ,
( / ,
) .

22.8.

749

IndexedDB :
,
, ,
, . In
dexedDB ,
, .
IndexedDB .
,
( ).
, .
, get()
put(). ( add(),
.)
, IDBRange
openCursor() . ,
,
get() openCursor() -.
,
, -
, ,
. ( IndexedDB

,
, .) ,

. ,
put() get()
openCursor() .
.
success error
, ,
onsuccess onerror. onsuccess
result .

.
IndexedDB .
, onsuccess.
,
, .
get() put() .
,
, , get() put(),
.
, ,
abort() .

commit(), . IndexedDB
onsuccess,

750

22. HTML5

, ,
, (
). , ,
, .
IndexedDB
, ,
.
, ,
IndexedDB.
IndexedDB API :
.
, ,
(, ,
).
onsuccess , setVersion()
. setVersion()

. , setVersion()
, create
ObjectStore() createIndex() .
, IndexedDB,
22.15. IndexedDB
,
, . , ,
IndexedDB.
Firefox4 Chrome11, - ,
,
, , ,
.
. 22.15 ,
, .
22.15. IndexedDB
<!DOCTYPE html>
<html>
<head>
<title>Zipcode Database</title>
<script>
// IndexedDB
var indexedDB = window.indexedDB || // API
window.mozIndexedDB || // Firefox
window.webkitIndexedDB; // Chrome
// Firefox :
var IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction;
var IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange;
//
function logerr(e) {
console.log(" IndexedDB " + e.code + ": " + e.message);
}

22.8.

751

// (
// ) f().
function withDB(f) {
var request = indexedDB.open("zipcodes"); // zipcode
request.onerror = logerr; //
request.onsuccess = function() { //
var db = request.result; //
// , .
// , , .
// - . ,
// f().
if (db.version === "1") f(db); // , f()
else initdb(db,f); //
}
}
// , , ,
// .
function lookupCity(zip, callback) {
withDB(function(db) {
//
var transaction = db.transaction(["zipcodes"], //
IDBTransaction.READ_ONLY, //
0); //
//
var objects = transaction.objectStore("zipcodes");
// , .
// ,
var request = objects.get(zip);
request.onerror = logerr; //
request.onsuccess = function() { //
// request.result
var object = request.result;
if (object) // . ,
callback(object.city + ", " + object.state);
else //
callback(" ");
}
});
}
//
// ( ) ( ).
//
function lookupZipcodes(city, callback) {
withDB(function(db) {
// ,
var transaction = db.transaction(["zipcodes"], IDBTransaction.READ_ONLY, 0);
var store = transaction.objectStore("zipcodes");
//
var index = store.index("cities");
// , ,
// , .
// , ,
var range = new IDBKeyRange.only(city); //

752

22. HTML5

// , , .
// , .
var request = index.openCursor(range); //
request.onerror = logerr; //
request.onsuccess = function() { //
// ,
// , ,
// , .
var cursor = request.result // request.result
if (!cursor) return; // =
var object = cursor.value //
callback(object); //
cursor.continue(); //
};
});
}
// onchange .
//
function displayCity(zip) {
lookupCity(zip, function(s) { document.getElementById('city').value=s; });
}
// , onchange .
//
function displayZipcodes(city) {
var output = document.getElementById("zipcodes");
output.innerHTML = " :";
lookupZipcodes(city, function(o) {
var div = document.createElement("div");
var text = o.zipcode + ": " + o.city + ", " + o.state;
div.appendChild(document.createTextNode(text));
output.appendChild(div);
});
}
// ,
// f(). withDB(),
// . , .
function initdb(db, f) {
//
//
// . , .
var statusline = document.createElement("div");
statusline.style.cssText =
"position:fixed; left:0px; top:0px; width:100%;" +
"color:white; background-color: black; font: bold 18pt sans-serif;" +
"padding: 10px; ";
document.body.appendChild(statusline);
function status(msg) { statusline.innerHTML = msg.toString(); };
status(" ");
// ,
// IndexedDB - onsucess setVersion.
var request = db.setVersion("1"); //
request.onerror = status; //
request.onsuccess = function() { //

22.8.

753

// .
// : {
// zipcode: "02134", // Zoom!1 :-)
// city: "Allston",
// state: "MA",
// latitude: "42.355147",
// longitude: "-71.13164"
// }
//
// "zipcode"
// ,
// , ,
// " ", -
// . ( , IndexedDB
// .)
var store = db.createObjectStore("zipcodes", //
{ keyPath: "zipcode" });
// .
// ,
// , .
store.createIndex("cities", "city");
// ,
// .
//
// :
//
// 02130,Jamaica Plain,MA,42.309998,-71.11171
// 02131,Roslindale,MA,42.284678,-71.13052
// 02132,West Roxbury,MA,42.279432,-71.1598
// 02133,Boston,MA,42.338947,-70.919635
// 02134,Allston,MA,42.355147,-71.13164
//
// ,
// ,
// : http://mappinghacks.com/2008/04/28/civicspace-zip-code-database/
// XMLHttpRequest.
//
// onload onprogress, XHR2
var xhr = new XMLHttpRequest(); // XHR
xhr.open("GET", "zipcodes.csv"); // HTTP- GET URL
xhr.send(); //
xhr.onerror = status; //
1

19721978 . WGBH-TV ZOOM.


,
. , , , ,
, , ,
, , , .
: ZOOM, ---, 3-5-0,
, 0-2-1-3-4 ZOOM!. ,
, . : http://en.wikipedia.org/wiki/ZOOM_
(1972_TV_series). . .

754

22. HTML5

var lastChar = 0, numlines = 0; //


// ,
xhr.onprogress = xhr.onload = function(e) { // !
// lastChar
// . (
// , )
var lastNewline = xhr.responseText.lastIndexOf("\n");
if (lastNewline > lastChar) {
var chunk = xhr.responseText.substring(lastChar, lastNewline)
lastChar = lastNewline + 1; //
//
var lines = chunk.split("\n");
numlines += lines.length;
// ,
// .
// , ,
// ,
// .
// , ,
// (
// ). , ,
// , :
var transaction = db.transaction(["zipcodes"], //
IDBTransaction.READ_WRITE);
//
var store = transaction.objectStore("zipcodes");
// ,
// .
for(var i = 0; i < lines.length; i++) {
var fields = lines[i].split(",");//
var record = { //
zipcode: fields[0], // -
city: fields[1],
state: fields[2],
latitude: fields[3],
longitude: fields[4]
};
// IndexedDB API ,
// *-* .
// :
store.put(record); // add(),
}
status(" , : "
+ numlines + ".");
}
if (e.type == "load") {
// load, ,
// . ,
// 40000 ,
// . .

22.9. -

755

// , ,
// ,
// f(), withDB()
lookupCity("02134", function(s) { // Allston, MA
document.body.removeChild(statusline);
withDB(f);
});
}
}
}
}
</script>
</head>
<body>
<p> , :</p>
: <input onchange="displayCity(this.value)"></input>
: <output id="city"></output>
</div>
<div>
<p> ( , ),
:</p>
: <input onchange="displayZipcodes(this.value)"></input>
<div id="zipcodes"></div>
</div>
<p><i> Firefox4 Chrome11.</i></p>
<p><i> .</i></p>
<p><i> Chrome --unlimited-quota-forindexeddb</i></p>
</body>
</html>

22.9. -
18 , JavaScript
.
HTTP, ,
HTTP: , ,
. HTTP
.
( )

TCP-.
JavaScript TCP-,
WebSocket API :

, -.
.
- .
WebSocket():
var socket = new WebSocket("ws://ws.example.com:1234/resource");

756

22. HTML5

-
- JavaScript,
-,
.
-;
,
Node (12.2)
-.
TCP-, , -
. ,
, - ,
- HTTP-
- .
-
. , -
,
-
, . Firefox4,
, -,
about:config network.websocket.
override-security-block true.

WebSocket() URL-,
ws:// ( wss:// ,
https://). URL- ,
, ( -
, HTTP HTTPS) .
:
socket.onopen = function(e) { /*
socket.onclose = function(e) { /*
socket.onerror = function(e) { /*
socket.onmessage = function(e) {
var message = e.data; /*
};

. */ };
. */ };
- ! */ };
. */

, send() :
socket.send(", !");

-
UTF-8.
-
, , ,
.
-
close().

22.9. -

757

- , ,
-,
.
. , -
,
. ,
,
. , -
, ,
, . WebSocket()
. ,
. , ,
. ,
, protocol WebSocket.
18.3 EventSource
. .
22.16 : 18.15,
-
EventSource XMLHttpRequest .
22.16. -
<script>
window.onload = function() {
//
var nick = prompt(" "); //
var input = document.getElementById("input"); //
input.focus(); //
// - .
// , HTTP-, ,
// -,
// , http:// ws://
var socket = new WebSocket("ws://" + location.host + "/");
// -
socket.onmessage = function(event) { //
var msg = event.data; //
var node = document.createTextNode(msg); //
var div = document.createElement("div"); // <div>
div.appendChild(node); //
document.body.insertBefore(div, input); // div
input.scrollIntoView(); // input
}
// -
input.onchange = function() { // Enter
var msg = nick + ": " + input.value; //
socket.send(msg); //
input.value = ""; //
}
};
</script>
<!-- -->

758

22. HTML5

<!-- -->
<input id="input" style="width:100%"/>

22.17 , -
, Node
(12.2). 18.17, , -
, .
22.17. -,
Node
/*
* JavaScript
* NodeJS. -,
* HTTP- websocket,
* : https://github.com/miksago/node-websocket-server/.
* "/" HTML- .
* 404.
* - .
*/
var http = require('http'); // HTTP- Node
var ws = require('websocket-server'); //
// . .
var clientui = require('fs').readFileSync("wschatclient.html");
// HTTP-
var httpserver = new http.Server();
// HTTP- ,
httpserver.on("request", function (request, response) {
// "/", .
if (request.url === "/") { //
response.writeHead(200, {"Content-Type": "text/html"});
response.write(clientui);
response.end();
}
else { // 404 "Not Found"
response.writeHead(404);
response.end();
}
});
// HTTP- -
var wsserver = ws.createServer({server: httpserver});
//
wsserver.on("connection", function(socket) {
socket.send(" ."); //
socket.on("message", function(msg) { //
wsserver.broadcast(msg); //
});
});
// 8000. -
// HTTP-.
// http://localhost:8000/.
wsserver.listen(8000);

III
III.

JavaScript

,
JavaScript.
, :
Arguments EvalError Number String
Array Function Object SyntaxError
Boolean Global RangeError TypeError
Date JSON ReferenceError URIError
Error Math RegExp


, . ,
replace() String, String.replace(),
replace.
JavaScript ,
eval() NaN. .
,
.
JavaScript Glo
bal ( ).

JavaScript

arguments[]

arguments

arguments[] ,
Arguments .
, .
arguments , , ,
. Arguments
.

.
Arguments; 8

Arguments

ObjectArguments

arguments
arguments[n]

Arguments .
, ,
, length, .
, .
0 , 1 .. ,
, Arguments
, .

callee
length

.
, ,
Arguments.

762

JavaScript

, Arguments,
arguments Arguments.
Arguments ,
, .
length, Arguments
callee, .
Arguments
callee. Array,
Arguments.length , Array.length,
.
Arguments
. ,
Arguments ,
. Arguments
.
,
Arguments, Arguments ,
.

.
Function; 8

Arguments.callee

arguments.callee

arguments.callee , .
.
.

// callee
// ,
var factorial = function(x) {
if (x < 2) return 1;
else return x * arguments.callee(x1);
}
var y = factorial(5); // 120

Arguments.length
,

arguments.length

Array

763

length Arguments ,
. .
:
, .
Function.length. , ,
, Array.length.

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

.
Array.length, Function.length

Array

ObjectArray

new Array()
new Array()
new Array(0, 1, ..., n)

. (length)
.
0, ... n
.
Array() ,
, length
.


. Array()
, , length 0.

764

JavaScript


.
.
Array() ( new),
, new.

RangeError

Array() ,
RangeError,
232 1.


ECMAScript v3 .
, ,
, .
. :
var a = [1, true, 'abc'];
var b = [a[0], a[0]*2, f(x)];

length

, ,
, ,
, .
.

every(), filter(), forEach(), indexOf(), lastIndexOf(), map(), reduce(), reduceRight()


some() ECMAScript5, ,
IE, ES5.
concat()
.
every()
, true
.
filter()
,
-.
forEach()
.
indexOf()
.
join()

.
lastIndexOf() .
map()
.
pop()
.
push()
.
reduce()
.
reduceRight() .
reverse()
.
shift()
.
slice()
.

765

Array.concat()

, true
.
sort()
.
splice()
, .
toLocaleString() .
toString()
.
unshift()
.
some()

JavaScript, 7.

.
7

Array.concat()

.concat(, ...)

, ...

, .


,
.

concat() ,
. .
- 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]]

.
Array.join(), Array.push(), Array.splice()

Array.every()

EcmaScript 5

, true

.every()
.every(, o)

766

JavaScript

-,
o
this, .


true, true ( - )
, false, false ( - )
.

every() .

. false (
, false),
every() false.
true, every() true.
every() true.
i :
([i], i, )


. true ,
, . false
, .
Array.forEach().

[1,2,3].every(function(x) { return x < 5; }) // => true: < 5


[1,2,3].every(function(x) { return x < 3; }) // => false: < 3
[].every(function(x) { return false; }); // => true: true []

.
Array.filter(), Array.forEach(), Array.some()

Array.filter()

ECMAScript5

.map()
.map(, o)

, ,
.
o
this, .


, ,
true ( ).

Array.forEach()

767

filter() ,
true ( ). filter()
( ).
filter()
. i
:
([i], i, )

true , i
. filter()
, .
Array.forEach().

[1,2,3].filter(function(x) { return x > 1; }); // => [2,3]

.
Array.every(), Array.forEach(), Array.indexOf(), Array.map(), Array.reduce()

Array.forEach()

ECMAScript5

.forEach(f)
.forEach(f, o)

f
o

, .
this, f.

forEach()
f . i f
:
f([i], i, )

, f, . ,
forEach() . , .

forEach(),
map(), filter(), every() some().

. o,
o. this o.

768

JavaScript

, ( )
this
null .
.
,
. ,
,
.

.

var a = [1,2,3];
a.forEach(function(x,i,a) { a[i]++; }); // a [2,3,4]

.
Array.every(), Array.filter(), Array.indexOf(), Array.map(), Array.reduce()

Array.indexOf()

ECMAScript5

.indexOf()
.indexOf(, )

, .
, .
, 0.


>= , === , 1,
.

, ,
. ,
, 0
,
. ===.
1, .

['a','b','c'].indexOf('b') // => 1
['a','b','c'].indexOf('d') // => -1
['a','b','c'].indexOf('a',1) // => -1

.
Array.lastIndexOf(), String.indexOf()

769

Array.join()

Array.join()

.join()
.join()

,
. ,
.


,
.

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

a = new Array(1, 2, 3, "testing");


s = a.join("+"); // s "1+2+3+testing"

.
String.split()

Array.lastIndexOf()

ECMAScript5

.lastIndexOf()
.lastIndexOf(, )

.
, .
, .


<= , === , 1,
.

, ,
, ,

770

JavaScript

. ,
; .
===.
1, .

.
Array.indexOf(), String.lastIndexOf()

Array.length

.length

length ,
. ,
0,
length .
length Array(). length,
:
a = new Array(); //
b = new Array(10); //
c = new Array("one", "two", "three"); //
c[3] = "four"; //
c[10] = "blastoff"; //

a.length
b.length
c.length
c.length
c.length

0
10
3
4
11

, length.
length ,
. length ( ),
, , ,
undefined.

Array.map()

ECMAScript5

.map(f)
.map(f, o)

f
o

, .
.
this, f.


, f.

771

Array.pop()

map() , ,
, f. map()
f
. i f ,
i :
a[i] = f(array[i], i, array)

map() f
, .
Array.forEach().

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

.
Array.every(), Array.filter(), Array.forEach(), Array.indexOf(), Array.reduce()

Array.pop()

.pop()

pop() ,
. , pop()
undefined.

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

stack:
stack:
stack:
stack:
stack:
stack:

.
Array.push()

Array.push()

.push(, ...)

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

772

JavaScript

, ...
, .

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

.
Array.pop()

Array.reduce()

ECMAScript5

.reduce(f)
.reduce(f, _)

f , ( )
.
_
. ,
reduce() ,
.


,
f.

reduce() f.
: ,
. n
, f reduce()
n-1 . (,
1.)
f .
f ,
1

fold
inject.
. . .

Array.reduceRight()

773

, ( ) .
reduce().
reduce() _
. _ , reduce() ,
(
). , reduce()
, _ ,
f. f
_ .
_, n+1 (n _
) f n .
_ , reduce()
TypeError. _ , reduce()
_, f .
_ , reduce() ,
f.
f, reduce()
.
, . f
, .

[1,2,3,4].reduce(function(x,y) { return x*y; }) // => 24: ((1*2)*3)*4

.
Array.forEach(), Array.map(), Array.reduceRight()

Array.reduceRight()

ECMAScript5

.reduceRight(f)
.reduceRight(f, _)

f , ( )
.
_
. ,
reduceRight() ,
.


,
f.

reduceRight() reduce(): n-1 f


n . reduceRight()

774

JavaScript

reduce() ,
( ), . .
Array.reduce().

[2, 10, 60].reduceRight(function(x,y) { return x/y }) // => 3: (60/10)/2

.
Array.reduce()

Array.reverse()

.reverse()

reverse() Array
. , ..
, . ,
.

a = new Array(1, 2, 3); // a[0] == 1, a[2] == 3;


a.reverse(); // a[0] == 3, a[2] == 1;

Array.shift()

.shift()

shift() ,
.
, shift() undefined.
: shift() , .
shift() Array.pop() ,
, . shift() unshift().

var a = [1, [2,3], 4]


a.shift(); // 1; a = [[2,3], 4]
a.shift(); // [2,3]; a = [4]

.
Array.pop(), Array.unshift()

775

Array.slice()

Array.slice()

.slice(, )

, .
,
. , 1 , 2
..
,
. ,
, , .
, .


, ,
, , , .

slice() , , .
, ,
, , . ,
,
, .
: slice() .
Array.splice().

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]; IE 4 , [1,2,3]

Internet Explorer 4 .
IE .

.
Array.splice()

Array.some()
, true

.some()
.some(, o)

ECMAScript5

776

JavaScript

- .
this .


true, true ( )
, false, false ( ) .

some() , .

. true (
, true), some()
true.
false ( , false),
some() false. some() false.
every().
Array.every() Array.forEach().

[1,2,3].some(function(x) { return x > 5; }) // => false: > 5


[1,2,3].some(function(x) { return x > 2; }) // => true: > 3
[].some(function(x) { return true; }); // => false: false []

.
Array.every(), Array.filter(), Array.forEach()

Array.sort()

.sort()
.sort(orderfunc)

orderfunc

, .


. , ,
.

sort() .
sort() ,
(, ,
). , ,
.
- ,
, ,

Array.splice()

777

.
, a b, :
,
a b
b.
, a b .
, a b.
,
. ,
: orderfunc.

, ,
, :
//
function numberorder(a, b) { return a b; }
a = new Array(33, 4, 1111, 222);
a.sort(); // : 1111, 222, 33, 4
a.sort(numberorder); // : 4, 33, 222, 1111

Array.splice()
,

.splice(, _, , ...)

, .
_
, , c
, , .
, 0.
, ...
, ,
, .


, , .

splice() , ,
, ,
, . ,
,
. , ,
, slice(), splice()
.

778

JavaScript

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

.
Array.slice()

Array.toLocaleString()

Object.toLocaleString()

.toLocaleString()

TypeError

, .

toLocaleString()
. toLocaleString()
-
, .

.
Array.toString(), Object.toLocaleString()

Array.toString()

Object.toString()

.toString()

TypeError

, .

toString() .
, JavaScript
.
toString().

779

Array.unshift()

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

.
Array.toLocaleString(), Object.toString()

Array.unshift()

.unshift(, ...)

,
.

, ...

unshift() ,
. unshift()
,
.. : unshift() ,
.

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

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

1
2
22
3

.
Array.shift()

Boolean

ObjectBoolean

new Boolean() // -
Boolean() //

, Boolean
.

780

JavaScript


( new) Boolean()
Boolean, .
( new) Boolean()
.
0, NaN, null, "" undefined false.
, false ( "false"),
true.

toString()
valueOf()

"true" "false" ,
Boolean.
,
Boolean.

JavaScript. Boolean
. Boolean
toString(),
. toString()
( JavaScript
), Boolean,
toString().

.
Object

Boolean.toString()

Object.toString()

b.toString()


"true" "false" , b:
Boolean.

TypeError

, Boolean.

Boolean.valueOf()
Boolean

Object.valueOf()

b.valueOf()


, b,
Boolean.

781

Date

TypeError

, Boolean.

Date

ObjectDate

new Date()
new Date()
new Date(_)
new Date(, , , , , , )
Date() Date ,
.
,
, , getTime().
,
, Date.parse(). ,
, .
, , .
: ,
UTC (Universal Coordinated Time
), GMT (Greenwich Mean Time ).
Date.UTC().
Date() ( new).
Date() .

1
1970 (UTC). , 5000,
, 1
1970.
, ()
. , Date.parse().
. , 2001 2001.
JavaScript
1900, 0 99.
, 0 () 11 ().
, 1 31. ,
1,
0. .
, 0 () 23 (11 ).
.
, 0 59.
.
, 0 59.
.
, 0 999.
.

782

JavaScript

Date ;
.
Date : ,
(UTC GMT). UTC,
.
. , get[UTC]Day()
: getDay() getUTCDay().
Date Date
TypeError, .
get[UTC]Date()
Date
.
get[UTC]Day()
Date
.
get[UTC]FullYear()

.
get[UTC]Hours()
Date .
get[UTC]Milliseconds()
Date
.
get[UTC]Minutes()
Date .
get[UTC]Month()
Date .
get[UTC]Seconds()
Date .
getTime()
() Date.
: , ,
getUTCTime() .
getTimezoneOffset()

. : ,
.
getYear()
Date. ,
getFullYear().
set[UTC]Date()
Date
.

Date

783

set[UTC]FullYear()
(, , ) Date
.
set[UTC]Hours()
(, , , ) Date
.
set[UTC]Milliseconds()
Date
.
set[UTC]Minutes()
(, , ) Date
.
set[UTC]Month()
(, , ) Date
.
set[UTC]Seconds()
(, , ) Date
.
setTime()
Date .
setYear()
Date. ,
setFullYear().
toDateString()
, Date .
toGMTString()
Date , GMT. ,
toUTCString().
toISOString()
Date , ISO-8601,
/ UTC.
toJSON()
Date JSON toISOString().
toLocaleDateString()
, Date
.
toLocaleString()
Date
.
toLocaleTimeString()
, Date
.
toString()
Date .

784

JavaScript

toTimeString() , Date
.
toUTCString() Date , .
valueOf()
Date .


Date
. Date(),
Date:
Date.now()
.
Date.parse()
.
Date.UTC()
UTC
.

Date , JavaScript. Date


new Date().
Date
. , , ,
, , ,
UTC (, GMT). toString()
. getTime() setTime()
, (GMT) 1 1970,
Date .
,
. ECMAScript , Date
100
01.01.1970. 273 785 , JavaScript-
275 755.

, Date:
d = new Date(); //
document.write(': "+d.toLocaleDateString() + '. ');//
document.write(': '+ d.toLocaleTimeString()); //
var dayOfWeek = d.getDay(); //
var weekend = (dayOfWeek == 0) || (dayOfWeek == 6); //

Date

.
:
<script language="JavaScript">
today = new Date(); //
christmas = new Date(); //
christmas.setMonth(11); // ...
christmas.setDate(25); // 25-
// ,
// ,

Date.getDate()

785

if (today.getTime() < christmas.getTime()) {


difference = christmas.getTime() - today.getTime();
difference = Math.floor(difference / (1000 * 60 * 60 * 24));
document.write(' ' + difference + ' !<p>');
}
</script>
// ... HTML- ...
<script language="JavaScript">
// Date
// 1000
now = new Date();
document.write('<p> ' +
(now.getTime()-today.getTime())/1000 +
'.');
</script>

.
Date.parse(), Date.UTC()

Date.getDate()
Date

.getDate()


, Date,
. 1 31.

Date.getDay()
Date

.getDay()


, Date,
. 0 () 6 ().

Date.getFullYear()
Date

.getFullYear()


, , .
, .

786

JavaScript

Date.getHours()
Date

.getHours()


, Date, .
0 () 23 (11
).

Date.getMilliseconds()
Date

.getMilliseconds()


, Date,
.

Date.getMinutes()
Date

.getMinutes()


e, Date,
. 0 59.

Date.getMonth()
Date

.getMonth()


, Date,
. 0 () 11 (
).

Date.getSeconds()
Date

.getSeconds()

Date.getTime()

787


, Date, .
0 59.

Date.getTime()

.getTime()


, Date, ..
01.01.1970 /, .

getTime() . ,
Date ,
. :
, getUTCTime(), .
getTime() getDay() getDate(), , ,
.
Date.parse() Date.UTC()
, Date.

.
Date, Date.parse(), Date.setTime(), Date.UTC()

Date.getTimezoneOffset()
GMT

.getTimezoneOffset()


(GMT) .

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

Date.getUTCDate()
Date ( )

.getUTCDate()

788

JavaScript


( 1 31),
.

Date.getUTCDay()
Date ( )

.getUTCDay()


, , .
0 () 6 ().

Date.getUTCFullYear()
Date ( )

.getUTCFullYear()


, , .
, .

Date.getUTCHours()
Date ( )

.getUTCHours()


, .
0 () 23 (11 ).

Date.getUTCMilliseconds()
Date ( )

.getUTCMilliseconds()


, .

Date.getUTCMinutes()
Date ( )

.getUTCMinutes()

789

Date.getUTCMonth()


, .
0 59.

Date.getUTCMonth()
Date ( )

.getUTCMonth()


, , .
0 () 11 (). : Date
1, 0.

Date.getUTCSeconds()
Date ( )

.getUTCSeconds()


, . 0
59.

Date.getYear()

Date

.getYear()


, Date, 1900.

getYear() Date 1900.


ECMAScript v3,
JavaScript; getFullYear().

Date.now()

ECMAScript5

Date.now()


, 1 1970
.

790

JavaScript

ECMAScript5
:
Date.now = function() { return (new Date()).getTime(); }

.
Date, Date.getTime()

Date.parse()
/

Date.parse()

, .


/ 1
1970 .

Date.parse() Date. Date.parse()


, , ,
, .
Date
Date Date.setTime().
ECMAScript5 , ,
Date.toISOString(). ECMAScript5
, ,
toString() toUTCString().

.
Date, Date.setTime(), Date.toISOString(), Date.toString()

Date.setDate()
Date

.setDate(_)

1 31, (
) .


. ECMAScript
.

Date.setFullYear()

791

Date.setFullYear()
, , Date

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

, ,
. , ,
1999; , 99.
0 11,
( ) .
1 31,
( ).

Date.setHours()
, , Date

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

0 () 23 (11 ) ,
.
0 59,
( ).
ECMAScript.
0 59.
( ).
ECMAScript.
0 999,
( ).
ECMAScript.


. ECMAScript
.

792

JavaScript

Date.setMilliseconds()
Date

.setMilliseconds()

, ,
. 0 999.

Date.setMinutes()
, Date

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

0 59, (
) , Date.
0 59,
( ).
ECMAScript.
0 999,
( ) .
ECMAScript.


. ECMAScript
.

Date.setMonth()
Date

.setMonth()
.setMonth(, )

0 () 11 (),
( ) ,
Date. : , 0,
1.

Date.setSeconds()

793

1 31,
( ).
ECMAScript.


. ECMAScript
.

Date.setSeconds()
Date

.setSeconds()
.setSeconds(, )

0 59, ,
Date.
0 999,
( ).
ECMAScript.


. ECMAScript
.

Date.setTime()

.setTime()

/
1 1970 .
Date()
Date.UTC() Date.parse().
.


. ECMAScript .

Date.setUTCDate()
Date ( )

.setUTCDate(_)

794

JavaScript

,
. 1 31.

Date.setUTCFullYear()
,
Date ( )

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

, , .
, , 1999,
, 99.
0 11,
( ). :
, 0, 1.
1 31;
( ) .

Date.setUTCHours()
, ,
Date ( )

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

, ,
. 0 () 23 (11
).
0 59,
( ).
0 59,
( ).

Date.setUTCMilliseconds()

795

0 999,
( ).

Date.setUTCMilliseconds()
Date ( )

.setUTCMilliseconds()

, ,
. 0 999.

Date.setUTCMinutes()
,
Date ( )

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

.
0 59.
0 59,
( ).
0 999,
( ).

Date.setUTCMonth()
Date ( )

.setUTCMonth()
.setUTCMonth(, )

, , .
0 () 11 ().
: , 0, 1.

796

JavaScript

1 31,
( ).

Date.setUTCSeconds()
Date ( )

.setUTCSeconds()
.setUTCSeconds(, )

.
0 59.
0 999,
( ).

Date.setYear()

Date

.setYear()

, ( ) ,
Date. 0 99,
1900, 1900 1999.


. ECMAScript
.

setYear() Date,
1900 1999.
ECMAScript v3,
JavaScript; setFullYear().

Date.toDateString()
Date

.toDateString()

Date.toGMTString()

797


(
), .

.
Date.toString(), Date.toTimeString()

Date.toGMTString()

Date

.toGMTString()


, .
, .

toGMTString() ,
Date.toUTCString().
ECMAScript v3 JavaScript
; toUTCString().

.
Date.toUTCString()

Date.toISOString()

ECMAScript5

Date ISO8601

.toISOString()


,
ISO-8601 UTC
Z. :
yyyy-mm-ddThh:mm:ss.sssZ

.
Date.parse(), Date.toString()

Date.toJSON()
Date JSON

.toJSON()

ECMAScript5

798

JavaScript

toJSON()
JSON.stringify().


, toISOString().

Date JSON.strin
gify(). .

.
Date.toISOString(), JSON.stringify()

Date.toLocaleDateString()
Date

.toLocaleDateString()


(
) ,
.

.
Date.toDateString(), Date.toLocaleString(), Date.toLocaleTimeString(), Date.toString(), Date.
toTimeString()

Date.toLocaleString()

.toLocaleString()


.

.


toLocaleString()
.
,
. toLocaleString() ,
.

.
Date.toISOString(), Date.toLocaleDateString(), Date.toLocaleTimeString(), Date.toString(),
Date.toUTCString()

799

Date.toLocaleTimeString()

Date.toLocaleTimeString()
Date

.toLocaleTimeString()



,
.

.
Date.toDateString(), Date.toLocaleDateString(), Date.toLocaleString(), Date.toString(), Date.
toTimeString()

Date.toString()
Date

Object.toString()

.toString()

toString()
. toUTCString(), toString()
. toLocaleString(), toString()
.

.
Date.parse(), Date.toDateString(), Date.toISOString(), Date.toLocaleString(), Date.toTime
String(), Date.toUTCString()

Date.toTimeString()
Date

.toTimeString()


,
, .

.
Date.toString(), Date.toDateString(), Date.toLocaleTimeString()

800

JavaScript

Date.toUTCString()
Date ( )

.toUTCString()


,
.

toUTCString() ,
.

.
Date.toISOString(), Date.toLocaleString(), Date.toString()

Date.UTC()

Date.UTC(, , , , , , )

. 0 99,
1900, 1900 1999.

0 () 11 ().

1 31. :
1,
0. .

0 () 23 (11 ).
.
0 59.
.
0 59.
.

. ;
ECMAScript.


.
1 1970
.

Date.UTC() ,
Date(), Date.

801

Date.valueOf()

Date.UTC()
UTC. UTC ,
- Date() Date.setTime().
- Date() ,
, Date.UTC(). , Date()
, Date.UTC() (GMT). Date,
UTC, :
d = new Date(Date.UTC(1996, 4, 8, 16, 30));

.
Date, Date.parse(), Date.setTime()

Date.valueOf()
Date

Object.valueOf()

.valueOf()


.
, Date.getTime().

decodeURI()
URI

decodeURI(uri)

uri

, URI (Uniform Resource Identifier


) ,
.


uri,
, .

URIError , uri
.

decodeURI() ,
uri. , encodeURI();
. .

.
decodeURIComponent(), encodeURI(), encodeURIComponent(), escape(), unescape()

802

JavaScript

decodeURIComponent()
URI

decodeURIComponent(s)

, URI ,
.


s,
.

URIError ,
s .

decodeURIComponent() ,
s. ,
encodeURIComponent(); . .

.
decodeURI(), encodeURI(), encodeURIComponent(), escape(), unescape()

encodeURI()
URI

encodeURI(uri)

uri

, URI , .


uri,
.

URIError , uri
.

encodeURI() ,
uri. , ASCII:
- _ . ! ~ * ' ( )

encodeURI() URI ,
, URI , :

encodeURIComponent()

803

; / ? : @ & = + $ , #

uri
UTF-8
%xx.
ASCII- %xx,
\u0080 \u07ff , 16-
.
URI ,
URI (, ) URI, ? #. ,
encodeURI
Component().
decodeURI() , .
ECMAScript v3 escape() unescape(),
, .

// http://www.isp.com/app.cgi?arg1=1&arg2=hello%20world
encodeURI("http://www.isp.com/app.cgi?arg1=1&arg2=hello world");
encodeURI("\u00a9"); // %C2%A9

.
decodeURI(), decodeURIComponent(), encodeURIComponent(), escape(), unescape()

encodeURIComponent()
URI

encodeURIComponent(s)

, URI ,
.


s,
.

URIError , s
.

encodeURIComponent() ,
s. ,
ASCII:
- _ . ! ~ * ' ( )

, , / : #,
URI,

804

JavaScript

.
. , encodeURI().
encodeURIComponent() encodeURI():
encodeURIComponent() , URI (
, , ).
, URI.

encodeURIComponent("hello world?"); // hello%20world%3F

.
decodeURI(), decodeURIComponent(), encodeURI(), escape(), unescape()

Error

ObjectError

new Error()
new Error()


Error. , Error
message;
,
. Error() ( new),
, new.

message

name

.
, ,
, .
, . Error
,
.

toString()

, ,
Error.

Error
throw try/catch. name ,
message
.
JavaScript Error .
Error, SyntaxError

Error.message

805

RangeError.
Error
.
: ECMAScript Error
toString() ( Error), ,
, message.
, toString() Error , .
,
name message Error.

:
function factorial(x) {
if (x < 0) throw new Error("factorial: x >= 0");
if (x <= 1) return 1; else return x * factorial(x1);
}

,
( Window.alert()):
try { &*(&/* */ }
catch(e) {
if (e instanceof Error) { // Error ?
alert(e.name + ": " + e.message);
}
}

.
EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError

Error.message

error.message

message Error ( Error)


,
. Error() message,
message. message ,
Error ,
( ).

Error.name

error.name

806

JavaScript

name Error ( Error)


. Error
. .
, SyntaxError name SyntaxError, Eval
Error EvalError.

Error.toString()
Error

Object.toString()

error.toString()


, . ECMAScript
, , ,
. , ,
.

escape()

escape(s)

, (
).


s,
.

escape() , ,
s. s . escape()
, , s, ,
(@, *, _, +, , . /) ASCII,
%xx %uxxxx ( x
). \u0000 \u00ff
%xx, %uxxxx.
, escape(), unescape().
escape() ECMAScript,
ECMAScript v3. ECMAScript
, . escape()
encodeURI() encodeURIComponent().

escape("Hello World!"); // "Hello%20World%21"

807

eval()

.
encodeURI(), encodeURIComponent()

eval()
JavaScript-

eval()

, .


, , .

eval() SyntaxError,
JavaScript.
, eval()
.

eval() , ,
JavaScript. JavaScript-,
eval() .
JavaScript-, eval()
( ), .
, eval() undefined. ,
, eval() .
ECMAScript3 ECMAScript5
eval(). , ECMAScript5
. ,
.
, eval ,
. JavaScript eval ,
eval().
eval, , ,
eval.
eval() . eval()
, . ,
eval() , .
,
eval() :
, ES3 ES5
eval() .
,
. eval().

808

JavaScript

, ES3
ECMAScript 3
EvalError eval(). ES3
, .
, ES5
ECMAScript5,
EvalError, eval()
,
. ES5 var geval = eval;
geval() .
,

,
eval(). , eval()
,
. , eval()
use strict.
eval() JavaScript ,
.
, Java
Script JavaScript-.
JavaScript-, ,

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

eval("1+2"); // 3
// JavaScript-
// .
// . Window.alert() Window.prompt().
try {
alert(": " + eval(prompt(" :","")));
}
catch(exception) {
alert(exception);
}

EvalError
eval()

new EvalError()
new EvalError()

ObjectErrorEvalError

809

Function


. ,
message EvalError.


EvalError. , Error
message;
,
. EvalError() (
new), , new.

message

name

.
, ,
, . .
Error.message.
, . EvalError
EvalError.

EvalError , eval()
. eval()
.
, Error.

.
Error, Error.message, Error.name

Function
JavaScript

ObjectFunction

function _(_) //
{

}
function( _) { } //
_(_) //

new Function(_..., )

_...
,
Function.

810

JavaScript

, .
JavaScript, ,
, .


Function. Java
Script-, .

SyntaxError ,
_ .

arguments[] , . .
caller
Function, , null,
.
.
length
, .
prototype
, ,
,
.

apply()
bind()
call()
toString()

,
.
,
.
,
.
.

JavaScript . 8
, , 9
, , prototype .
. . :
Function(), ,

.
JavaScript 1.1
arguments, Arguments.
,
. arguments[], .
. Arguments.

.
Arguments; 8 9

811

Function.apply()

Function.apply()

.apply(_, )

_ , .
_ this.
null,
.

,
.


, .

TypeError

, ,
, ,
Arguments.

apply() , ,
_, ,
. , .
this _.
Arguments.
, ,
Function.call().

// Object.toString(), ,
// .
// .
Object.prototype.toString.apply(o);
// Math.max(),
// . : .
var data = [1,2,3,4,5,6,7,8];
Math.max.apply(null, data);

.
Function.call()

Function.arguments[]
,

.arguments[i]
.arguments.length

812

JavaScript

arguments Function ,
. .
arguments.length .
,
JavaScript-; Arguments.

.
Arguments

Function.bind()

ECMAScript5

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


, .
... ,
.


,
.

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

, f bind(),
:
var g = f.bind(o, 1, 2);

g, g(3)
:
f.call(o, 1, 2, 3);

.
Function.apply(), Function.call(), 8.7.4

Function.call()

.call(_, ...)

813

Function.caller

_ , .
_
this. null,
.
... , .


, .

TypeError

, ,
.

call() , ,
_, ,
_. call() ,
. this _
, _ null.
,
Function.apply().

// Object.toString(), ,
// .
// .
Object.prototype.toString.call(o);

.
Function.apply()

Function.caller

.caller

JavaScript caller Function


, .
JavaScript- , caller null.
(.. caller
, ).
Function.caller ECMAScript
, .

814

JavaScript

Function.length

.length

length ,
.
. Function
length Arguments, ,
. Arguments.length.

.
Arguments.length

Function.prototype

.prototype

prototype , .
, .
, , ,
prototype.
-, prototype
JavaScript 9.

.
9

Function.toString()

.toString()


, .

TypeError

, ,
.

toString() Function ,
. , Firefox IE,

Global

815

JavaScript-, function,
, ..
toString() eval().
, .

Global

ObjectGlobal

this


,
.
undefined undefined, Global.
undefined. ,
.
Infinity
, .
NaN
.
undefined
undefined.


, ,
-
. , parseInt()
parseInt(), Global.parseInt().
decodeURI()
, enco
deURI().
decodeURIComponent() , enco
deURIComponent().
encodeURI
URI,
.
encodeURIComponent
URI,
.
escape()
,
.
eval()
JavaScript
.
isFinite()
, .
isNaN
, (NaN).
parseFloat()
.
parseInt()
.
unescape()
, escape().


,
,

816

JavaScript

JavaScript-. -
:
Array
Array().
Boolean
Boolean().
Date
Date().
Error
Error().
EvalError
EvalError().
Function
Function().
JSON
,
JSON .
Math
, .
Number
Number().
Object
Object().
RangeError
RangeError().
ReferenceError ReferenceError().
RegExp
RegExp().
String
String().
SyntaxError
SyntaxError().
TypeError
TypeError().
URIError
URIError().

, JavaScript
.
, .
- , .
( ,
Global.) JavaScript-
this.
, ..
,
. Java
Script- , , parseInt(),
parseInt . ,
, , , Ja
vaScript- , .
, . Global()
.
JavaScript- ,
, .
ECMAScript ,
JavaScript ,
.
JavaScript, , Window,
-, JavaScript-.

Infinity

817

JavaScript
,
for/in:
var variables = ""
for(var name in this)
variables += name + "\n";

.
Window ( IV ); 3

Infinity
,

Infinity

Infinity , ,
. Infinity
for/in delete.
, Infinity , . ( Number.POSITIVE_
INFINITY .)

.
isFinite(), NaN, Number.POSITIVE_INFINITY

isFinite()
,

isFinite(n)


n ( ),
true, n (NaN) / false.

.
Infinity, isNaN(), NaN, Number.NaN, Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY

isNaN()
,

isNaN(x)

818

JavaScript


x (
), true, x false.

NaN Not-a-Number ( ).
NaN (
NaN), (, ).
isNaN() , , .
false, x
, NaN. true, x
NaN.
NaN ,
, . ,
NaN, x === NaN:
false.
x !== x: true, x NaN.
isNaN() ,
parseFloat() parseInt(), ,
.

isNaN(0); //
isNaN(0/0); //
isNaN(parseInt("3")); //
isNaN(parseInt("hello")); //
isNaN("3"); //
isNaN("hello"); //
isNaN(true); //
isNaN(undefined); //

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

false
true
false
true
false
true
false
true

.
isFinite(), NaN, Number.NaN, parseFloat(), parseInt()

JSON

ECMAScript5

JSON

JSON ,
JSON.parse() JSON.stringify(), ECMAScript5.
JSON . , ECMAScript 5,
JSON
http://json.org/json2.js.
JSON JavaScript Object Notation ( Java
Script-). JSON ,
JavaScript, null,
true false, (

JSON.parse()

819

JavaScript), (
), (
) (
). undefined, NaN Infi
nity JSON. , Date, RegExp
Error .

// ,
// JSON
function deepcopy(o) { return JSON.parse(JSON.stringify(o)); }

.
JSON.parse(), JSON.stringify(), 6.9, http://json.org

JSON.parse()

ECMAScript5

JSON

JSON.parse(s)
JSON.parse(s, reviver)

s
reviver

.
, ,
.


, , s
(, , reviver).

JSON.parse() ,
JSON. ,
, .
reviver
,
. , reviver
( ,
), s. reviver
. , ..
.
. , reviver
, . ,
s , .

, , reviver

.

820

JavaScript

reviver
. reviver ,
. reviver undefined (
),
, JSON.parse() .

JSON.parse() :
var data = JSON.parse(text);

JSON.stringify() Date ,
reviver .
undefined,
:
var data JSON.parse(text, function(name, value) {
// ,
if (name[0] == '_') return undefined;
// ISO 8601,
// Date.
if (typeof value === "string" &&
/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d.\d\d\dZ$/.test(value))
return new Date(value);
//
return value
});

.
JSON.stringify(), 6.9

JSON.stringify()

ECMAScript5

JSON.stringify(o)
JSON.stringify(o, filter)
JSON.stringify(o, filter, indent)

Arguments
o
filter
indent

, ,
JSON.
,
, , .
,
,
. ,
, .


JSON, o
filter indent.

JSON.stringify()

821

JSON.stringify() ,
JSON,
JSON.parse().
.
JSON.stringify()
, , , , null,
. ,
, ,
. JSON.stringify() ( ) toJSON(),
,
. toJSON()
, . Date
toJSON(), Date Date.
toISOString(). , JavaScript,
toJSON(), . ,
, toJSON() :
, .
JSON.stringify()
.

. ,
, toJSON(), .
, . this
,
.
,
. .
undefined , (
) .
(
), .
, , .
, ,
.
JSON.stringify()
.
, . 1 10,
JSON.stringify()
.
, JSON.stringify()
( 10
) .

//
var text = JSON.stringify(data);
// ,
var text = JSON.stringify(address, ["city","state","country"]);

822

JavaScript

// , RegExp
var text = JSON.stringify(patterns, function(key, value) {
if (value.constructor === RegExp) return value.toString();
return value;
});
// :
RegExp.prototype.toJSON = function() { return this.toString(); }

.
JSON.parse(), 6.9

Math

Math.
Math.()

Math.E
Math.LN10
Math.LN2
Math.LOG10E
Math.LOG2E
Math.PI
Math.SQRT1_2
Math.SQRT2

e, .
10.
2.
e.
e 2.
.
, 2.
2.


Math.abs()
Math.acos()
Math.asin()
Math.atan()
Math.atan2()
Math.ceil()
Math.cos()
Math.exp()
Math.floor()
Math.log()
Math.max()
Math.min()
Math.pow()
Math.random()
Math.round()
Math.sin()

.
.
.
.
X .
.
.
e.
.
.
.
.
x y.
.
.
.

823

Math.abs()
Math.sqrt()
Math.tan()

.
.

Math , ,
.
:
y = Math.sin(x);
area = radius * radius * Math.PI;

Math , Date String. Math


Math(), , Math.sin(), ,
.

.
Number

Math.abs()

Math.abs(x)


x.

Math.acos()

Math.acos(x)

1,0 1,0.


x.
0 .

Math.asin()

Math.asin(x)

1,0 1,0.

824

JavaScript


x.
/2 /2 .

Math.atan()

Math.atan(x)


x.
/2 /2 .

Math.atan2()
X

Math.atan2(y, x)

y
x

Y .
X .


, ,
, X (x,y).

Math.atan2() y/x. y
Y ( ) , x X
( ) .
: Y X.

Math.ceil()

Math.ceil(x)


, x.

825

Math.cos()

Math.ceil() , .. ,
. Math.ceil() Math.
round() , , .
, Math.ceil()
; .

a
b
c
d

=
=
=
=

Math.ceil(1.99); //
Math.ceil(1.01); //
Math.ceil(1.0); //
Math.ceil(-1.99); //

2.0
2.0
1.0
-1.0

Math.cos()

Math.cos(x)

. ,
0,017453293 (2/360).


x.
1,0 1,0.

Math.E
e

Math.E

Math.E e, ,
2,71828.

Math.exp()
ex

Math.exp(x)

, .


ex e, x, e
, 2,71828.

826

JavaScript

Math.floor()

Math.floor(x)


, x.

, .. ,
.
Math.floor() , Math.
round(), . : Math.
floor() (.. ), (..
).

a
b
c
d

=
=
=
=

Math.floor(1.99); //
Math.floor(1.01); //
Math.floor(1.0); //
Math.floor(-1.01); //

1.0
1.0
1.0
-2.0

Math.LN10
log e10

Math.LN10

Math.LN10 loge10, 10. ,


2,3025850929940459011.

Math.LN2
log e2

Math.LN2

Math.LN2 loge2, 2. ,
0,69314718055994528623.

Math.log()

827

Math.log()

Math.log(x)

, .


x.

Math.log() .
.
10 2 :
log10x = log10e logex
log2x = log2e logex

JavaScript-:
function log10(x) { return Math.LOG10E * Math.log(x); }
function log2(x) { return Math.LOG2E * Math.log(x); }

Math.LOG10E
log10 e

Math.LOG10E

Math.LOG10E log10 e, 10 e.
0,43429448190325181667.

Math.LOG2E
log2e

Math.LOG2E

Math.LOG2E log2e, 2 e.
1,442695040888963387.

Math.max()

Math.max(...)

828

JavaScript

...


. -Infinity, .
NaN, - NaN ,
.

Math.min()

Math.min(...)

...


. Infinity, .
NaN, - NaN
, .

Math.PI

Math.PI

Math.PI , .. .
, 3,14159265358979.

Math.pow()
xy

Math.pow(x, y)

x
y

, .
, x.


x y (xy).

Math.pow() x y. x y .
, Math.pow() NaN.
, x , y

Math.random()

829

. ,
Infinity.

Math.random()

Math.random()


0,0 1,0.

Math.round()

Math.round(x)


, x.

Math.round() . 0,5
. , 2,5 3, 2,5 2.

Math.sin()

Math.sin(x)

.
0,017453293 (2/360).


x 1,0 1,0.

Math.sqrt()

Math.sqrt(x)

, 0.

830

JavaScript


x. NaN, x .

Math.sqrt() . ,
Math.pow(). :
Math.cuberoot = function(x){ return Math.pow(x,1/3); }
Math.cuberoot(8); // 2

Math.SQRT1_2
1/
2

Math.SQRT1_2

Math.SQRT1_2 1/
2, , 2.
0,7071067811865476.

Math.SQRT2

2

Math.SQRT2

Math.SQRT2
2, 2. ,
1,414213562373095.

Math.tan()

Math.tan(x)

, . ,
0,017453293 (2/360).


x.

NaN

NaN

Number

831

NaN ,
. NaN for/in
delete. : NaN ,
, .
, , isNaN(), ..
NaN ,
!

.
Infinity, isNaN(), Number.NaN

Number

ObjectNumber

new Number()
Number()

Number ,
.


Number() ( new),
Number. Number()
( new),
( NaN, ).

Number.MAX_VALUE
.
Number.MIN_VALUE
.
Number.NaN
.
Number.NEGATIVE_INFINITY
, .
Number.POSITIVE_INFINITY
; .

toString()
.
toLocaleString()
,
.

832

JavaScript

toFixed()
,
.
toExponential()

.
toPrecision()
,
.
.
valueOf()
Number.

JavaScript. JavaScript
Number,
. JavaScript
.
Number Number(),
.
Number() (
new).
( NaN),
.
Number()
: ,
, .
: -
Number(), . , MAX_VALUE
:
var biggest = Number.MAX_VALUE

:
var n = new Number(2);
var biggest = n.MAX_VALUE

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

Number. Number
, Number:
var value = 1234;
var binary_value = n.toString(2);

.
Infinity, Math, NaN

Number.MAX_VALUE

833

Number.MAX_VALUE

Number.MAX_VALUE

Number.MAX_VALUE , JavaScript.
1,79E+308.

Number.MIN_VALUE

Number.MIN_VALUE

Number.MIN_VALUE ( ,
), JavaScript. 5E324.

Number.NaN

Number.NaN

Number.NaN , ,
(,
) . parseInt() parseFloat()
, ;
Number.NaN ,
- , .
JavaScript Number.NaN NaN. :
NaN , NaN.
, , Number.NaN.
isNaN(). ECMAScript v1
Number.NaN
NaN.

.
isNaN(), NaN

Number.NEGATIVE_INFINITY

Number.NEGATIVE_INFINITY

834

JavaScript

Number.NEGATIVE_INFINITY , ,

, JavaScript (..
, -Number.MAX_VALUE).
JavaScript NEGATIVE_INFINITY -Infinity.
. , ,
, , , , . ECMA
Script v1
-Infinity Number.NEGATIVE_INFINITY.

.
Infinity, isFinite()

Number.POSITIVE_INFINITY

Number.POSITIVE_INFINITY

Number.POSITIVE_INFINITY , ,

, JavaScript
(.. Number.MAX_VALUE). :
, Number.MIN_VALUE, JavaScript .
JavaScript POSITIVE_INFINITY Infinity.
, . , -,
, , -, , . ECMA
Script v1 Number.POSITIVE_INFINITY
Infinity.

.
Infinity, isFinite()

Number.toExponential()

.toExponential()

. 0
20 ,
. ,
, .

835

Number.toFixed()



, ,
. , , ,
.

RangeError

TypeError

,
. 0 20
RangeError.
.
, ,
Number.

var n = 12345.6789;
n.toExponential(1); //
n.toExponential(5); //
n.toExponential(10); //
n.toExponential(); //

1.2e+4
1.23457e+4
1.2345678900e+4
1.23456789e+4

.
Number.toFixed(), Number.toLocaleString(), Number.toPrecision(), Number.toString()

Number.toFixed()

.toFixed()

;
0 20 ;
. ,
0.


,
.
,
. , 1e+21, Number.
toString() .

RangeError

TypeError

,
. 0 20
RangeError.
.
, ,
Number.

836

JavaScript

var n = 12345.6789;
n.toFixed(); //
//
n.toFixed(1); //
n.toFixed(6); //
(1.23e+20).toFixed(2); //
(1.23e10).toFixed(2) //

12346:

12345.7:
12345.678900:
123000000000000000000.00
0.00

.
Number.toExponential(), Number.toLocaleString(), Number.toPrecision(), Number. toString()

Number.toLocaleString()

.toLocaleString()


,
, , ,
, .

TypeError

, ,
Number.

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

Number.toPrecision()

.toPrecision()

.
1 21 .
. ,
toString().


, ,
. ,
,
.

-1 .
.

837

Number.toString()

RangeError

TypeError

,
. 1 21 Ran
geError.
.
, ,
Number.

var n = 12345.6789;
n.toPrecision(1); //
n.toPrecision(3); //
n.toPrecision(5); //
n.toPrecision(10); //

1e+4
1.23e+4
12346:
12345.67890:

.
Number.toExponential(), Number.toFixed(), Number.toLocaleString(), Number.toString()

Number.toString()

Object.toString()

.toString()

,
( 2 36), .
, 10. ,
ECMAScript
, , 10.

TypeError

, ,
Number.

toString() Number .
10, 10.
ECMAScript
,
2 36.

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

838

JavaScript

Number.valueOf()

Object.valueOf()

.valueOf()


Number.
.

TypeError

, ,
Number.

.
Object.valueOf()

Object
, JavaScript-

new Object()
new Object()


, ,
Number, Boolean String.


,
Object. ,
- Number, Boolean String .
Object() ( new),
, new.

constructor , .

hasOwnProperty()
, ( )
.
isPrototypeOf()
, .
propertyIsEnumerable()
,
for/in.

Object

839

toLocaleString()
.
toString(),
.
toString()
.
Object .
Object toString(),
.
valueOf()
, .
Object . Object,
Number Boolean, ,
, .


ECMAScript5 Object
:
Object.create()
.
Object.defineProperties()
.
Object.defineProperty()
.
Object.freeze()
.
Object.getOwnPropertyDescriptor()
.
Object.getOwnPropertyNames()
,
, for/in.
Object.getPrototypeOf()
.
Object.isExtensible()
, .
Object.isFrozen()
, .
Object.isSealed()
, ,
.
Object.keys()

.
Object.preventExtensions()
.

840

JavaScript

Object.seal()

.

Object JavaScript.
JavaScript-; ,
Object . Java
Script- 6.
Object()
,
6.1.

.
Array, Boolean, Function, Function.prototype, Number, String; 6

Object.constructor
-

.constructor

constructor ,
. , a
Array(), a.constructor Array:
a = new Array(1,2,3); //
a.constructor == Array // true

constructor
. typeof ,
. ,
constructor . ,
, :
function isArray(x) {
return ((typeof x == "object") && (x.constructor == Array));
}

, , ,
JavaScript, Java
Script, Window, .
Object.toString() .

.
Object.toString()

841

Object.create()

Object.create()

ECMAScript5

Object.create()
Object.create(, )


null.
,
.


, ,
.

TypeError

, null
Object.defineProper
ties() TypeError.

Object.create() ,
. ,
.
, Object.create()
, Object.defineProperties().
Object.create(p,d) :
Object.defineProperties(Object.create(p), d);


Object.defineProperties(),
Object.getOwnPropertyDescriptor().
, :
, .

// , x y z
var p = Object.create({z:0}, {
x: { value: 1, writable: false, enumerable:true, configurable: true},
y: { value: 2, writable: false, enumerable:true, configurable: true},
});

.
Object.defineProperty(), Object.defineProperties(), Object.getOwnPropertyDescriptor(),
6.1, 6.7

842

JavaScript

Object.defineProperties()

ECMAScript5

Object.defineProperties(o, )

Arguments
o
, .
, .


o.

TypeError

, o -
.
:
,
. , TypeEr
ror, 6.7.

Object.defineProperties() o,
.
, o,
,
.
Object.defineProperties() Object.defineProperty();
.
Object.
getOwnPropertyDescriptor().

//
var p = Object.defineProperties({},
x: { value: 0, writable: false,
y: { value: 1, writable: false,
});

x y,
{
enumerable:true, configurable: true},
enumerable:true, configurable: true},

.
Object.create(), Object.defineProperty(), Object.getOwnPropertyDescriptor(), 6.7

Object.defineProperty()

ECMAScript5

Object.defineProperty(o, , )

, .

Object.freeze()

843

.
,
, .


o.

TypeError

, o
(- , o
) (, - ,
). ,
TypeError, 6.7.

Object.defineProperty()
o, .
Object.getOwn
PropertyDescriptor().
o ,
, .
- , false
undefined.
o,
Object.defineProperty() ,
. ,
: , ,
.
, :
, .

function constant(o, n, v) { // o.n v


Object.defineProperty(o, n, { value: v, writable: false
enumerable: true, configurable:false});
}

.
Object.create(), Object.defineProperties(), Object.getOwnPropertyDescriptor(), 6.7

Object.freeze()

Object.freeze(o)

, .

ECMAScript5

844

JavaScript


o.

Object.freeze() o (Object.preventExtensions()),
, Object.seal().

. , o
, - .
Object.freeze() , ..
.
, Object.freeze() writable,
-. , .
, Object.freeze() .
, :
, .

.
Object.defineProperty(), Object.isFrozen(), Object.preventExtensions(), Object.seal(),
6.8.3

Object.getOwnPropertyDescriptor()

ECMAScript5

Object.getOwnPropertyDescriptor(o, )

, .
( ),
.


undefined,
.

Object.getOwnPropertyDescriptor()
. ,
.
. , :
, .


JavaScript-,
( ) . JavaScript .
-, : enumerable, writable configurable.
, / ,
enumerable configurable.

Object.getOwnPropertyNames()

845

:
{
value: /*
writable: /*
enumerable: /*
configurable: /*
}

, JavaScript */,
true false */,
true false */,
true false */

:
{
get: /*
set: /*
enumerable: /*
configurable: /*
}

undefined: value */,


undefined: writable */,
true false */,
true false */

.
Object.defineProperty(), 6.7

Object.getOwnPropertyNames()

ECMAScript5

Object.getOwnPropertyNames(o)


, o,
.

Object.getOwnPropertyNames()
o, .
Object.keys().
, :
, .

Object.getOwnPropertyNames([]) // => ["length"]: "length" -

.
Object.keys(), 6.5

Object.getPrototypeOf()

Object.getPrototypeOf(o)

ECMAScript5

846

JavaScript


o.

Object.getPrototypeOf() .
, :
, .

var p = {}; //
Object.getPrototypeOf(p) //
var o = Object.create(p) //
Object.getPrototypeOf(o) //


=> Object.prototype
, p
=> p

.
Object.create(); 6

Object.hasOwnProperty()
,

.hasOwnProperty(_)

_
, .


true, ,
_. false,
-.

9 , JavaScript- ,
-. hasOwnProperty()
,
.

var o = new Object(); //


o.x = 3.14; //
o.hasOwnProperty("x"); //
o.hasOwnProperty("y"); //
o.hasOwnProperty("toString"); //



true: x o
false: o y
false: toString

.
Function.prototype, Object.propertyIsEnumerable(); 9

847

Object.isExtensible()

Object.isExtensible()

ECMAScript5

Object.isExtensible(o)


true, , false .

, .
,
Object.preventExtensions(), Object.seal() Object.freeze().
, :
, .

var o = {}; //
Object.isExtensible(o) //
Object.preventExtensions(o); //
Object.isExtensible(o) //


=> true:

=> false:

.
Object.isFrozen(), Object.isSealed(), Object.preventExtensions(), 6.8.3

Object.isFrozen()

ECMAScript5

Object.isFrozen(o)


true, o , false .

, (
)
. , (
) ()
. Object.isFrozen() ,
. .
Object.freeze().
Object.preventExtensions()

848

JavaScript

Object.defineProperty(),
.
, :
, .

.
Object.defineProperty(), Object.freeze(), Object.isExtensible(), Object.isSealed(), Object.
preventExtensions(), Object.seal(), 6.8.3

Object.isPrototypeOf()
,

.isPrototypeOf(o)


true, o. false,
o o.

9, JavaScript
-.
prototype -,
. isPrototypeOf() ,
. .

var o = new Object(); //


Object.prototype.isPrototypeOf(o) // true: o
Function.prototype.isPrototypeOf(o.toString); // true: toString
Array.prototype.isPrototypeOf([1,2,3]); // true: [1,2,3]
//
(o.constructor == Object); // true: o Object()
(o.toString.constructor == Function); // true: o.toString
// - . true, ,
// - Function.prototype, Object.prototype.
Object.prototype.isPrototypeOf(Function.prototype);

.
Function.prototype, Object.constructor; 9

Object.isSealed()
?

Object.isSealed(o)

ECMAScript5

Object.keys()

849


true, o ,
, false .

, ,
()
() . Object.isSealed() ,
, ,
. .
Object.seal() Object.freeze().
Object.preventExtensions(),
Object.defineProperty(),
.
, :
, .

.
Object.defineProperty(), Object.freeze(), Object.isExtensible(), Object.isFrozen(), Object.
preventExtensions(), Object.seal(), 6.8.3

Object.keys()

ECMAScript5

Object.keys(o)


, () o.

Object.keys() o.
,
o: . (
Object.getOwnProperty
Names().) ,
for/in.
, :
, .

Object.keys({x:1, y:2}) // => ["x", "y"]

850

JavaScript

.
Object.getOwnPropertyNames(), 5.5.4, 6.5

Object.preventExtensions()

ECMAScript5

Object.preventExtensions(o)

, .


o .

Object.preventExtensions() false extensible


o, .
: .
, Object.preventExtensions()
,
.
, :
, .

.
Object.freeze(), Object.isExtensible(), Object.seal(), 6.8.3

Object.propertyIsEnumerable()
, for/in

.propertyIsEnumerable(_)

, .


true, ,
_, , ..
for/in .

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

. : ECMAScript , propertyIs

851

Object.seal()

Enumerable() , ..

.

var o = new Object(); //


o.x = 3.14; //
o.propertyIsEnumerable("x"); // true: x -
o.propertyIsEnumerable("y"); // false: o y
o.propertyIsEnumerable("toString"); // false: toString
Object.prototype.propertyIsEnumerable("toString"); // false:

.
Function.prototype, Object.hasOwnProperty(); 6

Object.seal()

ECMAScript5

Object.seal(o)

, ,
.


o.

Object.seal() o (Object.preventExtensions()),
.
. :

.
, Object.seal()
; Object.freeze(). , Object.seal()
. ,
Object.seal(), ,
.
, :
, .

.
Object.defineProperty(), Object.freeze(), Object.isSealed(), Object.preventExtensions(),
6.8.3

Object.toLocaleString()

.toString()

852

JavaScript

,
. toLocale
String(), Object, to
String() .
, , Array, Date Number,
.
.

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

Object.toString()

.toString()


, .

toString() , JavaScript. ,
, .
JavaScript toString()
, . ,
, :
alert(my_object);

,
+:
var msg = ' : ' + my_object;

toString() .
- , -
, .
JavaScript ,
toString(). , toString(),
Object. :
[object]

: , Object, String, Number, Func


tion, Window, Document .. toString()
.
toString(),
o Object.toString(), :

Object.valueOf()

853

Object.prototype.toString.apply(o);

,
. ,
Object.
Object.constructor.
toString() JavaScript-
.
toString() .
toString() ,
, . ,
, JavaScript :
y = Math.sqrt(x); //
ystr = y.toString(); //

,
toString(), .
toString()
, JavaScript .
toString() :
alert(my_obj.toString());

.
Object.constructor(), Object.toLocaleString(), Object.valueOf()

Object.valueOf()

.valueOf()


, , .
, .

valueOf() ,
, . Object ,
.
Number valueOf()
, .
, Boolean, ,
String.
valueOf(). Java
Script , ,
. - valueOf()

. typeof, ,
String, Java
Script- .

854

JavaScript

valueOf() Number, Boolean String -


. Object()
,
: -
. JavaScript
, Object()
.
valueOf()
. , JavaScript-
( ).
,
, ..
.
:
Complex.prototype.valueOf = new Function("return this.real");

valueOf() Complex, ,
, Math.sqrt(),
.

.
Object.toString()

parseFloat()

parseFloat(s)

,
.


NaN, s
. JavaScript 1.0, s , parseFloat()
0 NaN.

parseFloat()
, s. , parse
Float() s , . s
, parseFloat() ,
NaN. isNaN().
, parseInt(),
parseFloat().

.
isNaN(), parseInt()

855

parseInt()

parseInt()

parseInt(s)
parseInt(s, )

.
,
.
0,
( 0x 0X) .
2 36, parseInt() NaN.


(NaN, s ).
JavaScript 1.0, s,
parseInt() 0 NaN.

parseInt() s
( ), s.
, parseInt() s ,
. s ,
parseInt(),
NaN. isNaN().
. , 10,
parseInt() . 8,
( 0 7), 16
( 0 9 A F).
2 36.
0 , parseInt()
s. s ( )
0x, parseInt() s .
parseInt() .

parseInt("19", 10); //
parseInt("11", 2); //
parseInt("17", 8); //
parseInt("1f", 16); //
parseInt("10"); //
parseInt("0x10"); //

.
isNaN(), parseFloat()

19 (10 + 9)
3 (2 + 1)
15 (8 + 7)
31 (16 + 15)
10
16

856

JavaScript

RangeError
,

ObjectErrorRangeError

new RangeError()
new RangeError()

,
. ,
message RangeError.


RangeError. ,
RangeError message;
RangeError ,
. RangeError(), (
new), , new.

message

name

,
. ,
, ,
. . Error.message.
, . RangeError
RangeError.

RangeError ,
. ,
RangeError.
. Error.

.
Error, Error.message, Error.name

ReferenceError

ObjectErrorReferenceError

new ReferenceError()
new ReferenceError()

,
. ,
message ReferenceError.

RegExp

857


ReferenceError. , Refe
renceError message;
, . Reference
Error(), ( new), ,
new.

message ,
. , ,
, .
. Error.message.
name
, . ReferenceError
ReferenceError.

ReferenceError
.
. Error.

.
Error, Error.message, Error.name

RegExp

ObjectRegExp


//

new RegExp(, )

,
.
, g, i m,
,
, . ECMAScript m
. , ,
.


RegExp .
, ,
RegExp() RegExp, ,
RegExp. RegExp() (
new), , new, ,
RegExp; ,
RegExp.

858

JavaScript

,
,
g, i m.
, RegExp
.

SyntaxError

TypeError


RegExp g.
RegExp i.
;
.
RegExp m.
.

global
ignoreCase
lastIndex
multiline
source

.
, .

exec()
test()

RegExp
.
10.

.
10

RegExp.exec()

regexp.exec()

, .


, null,
. .

TypeError

, ,
RegExp.

exec() RegExp String


. , ,
RegExp.test(), String.search(), String.replace() String.match().

RegExp.global

859

exec() , regexp.
, ;
null. 0 . 1
, regexp,
. 2 .. length ,
, .
length , exec(), .
index . input
. ,
String.match(), RegExp.
exec() ,
. regexp
, exec() .
, regexp.lastIndex. ,
lastIndex
. , exec() ,
. exec() ,
null lastIndex .
,
lastIndex .
: exec()
, regexp
. exec() String.match(),
.
exec()
.

exec() :
var pattern = /\bJava\w*\b/g;
var text = "JavaScript is more fun than Java or JavaBeans!";
var result;
while((result = pattern.exec(text)) != null) {
alert("Matched `" + result[0] +
"' at position " + result.index +
" next search begins at position " + pattern.lastIndex);
}

.
RegExp.lastIndex, RegExp.test(), String.match(), String.replace(), String.search(); 10

RegExp.global

regexp.global

global RegExp, .
, , ..
g.

860

JavaScript

RegExp.ignoreCase

regexp.ignoreCase

ignoreCase RegExp, .
,
, .. i.

RegExp.lastIndex

regexp.lastIndex

lastIndex RegExp.
g ,
,
, RegExp.exec() RegExp.test().
.

. : lastIndex RegExp,
g .
,
, ,
. exec() test() lastIndex 0,
- ( ) .
,
0.

.
RegExp.exec(), RegExp.test()

RegExp.source

regexp.source

source RegExp,
RegExp. ,
, g,
i m.

861

RegExp.test()

RegExp.test()
,

regexp.test()


true, , regexp, false
.

TypeError

, ,
RegExp.

test() , , ,
regexp. , true, false.
test() r s
:
(r.exec(s) != null)

var pattern = /java/i;


pattern.test("JavaScript"); // true
pattern.test("ECMAScript"); // false

.
RegExp.exec(), RegExp.lastIndex, String.match(), String.replace(), String.substring();
10

RegExp.toString()

Object.toString()

regexp.toString()


regexp.

TypeError

, ,
RegExp.

RegExp.toString()
.

862

JavaScript

:
, ,
. ,
new RegExp("/", "g"). RegExp.toString()
///g
/\//g.

String

ObjectString

new String(s) // -
String(s) //

, String
.


String() ( new),
String, s s.
String(), new, s
.

length

, .
, .

.
indexOf()
.
lastIndexOf()
.
localeCompare()
.
match()
.
replace()

.
search()
,
.
slice()
.
split()
-
.
substr()
. substring().
substring()
.
charAt()
charCodeAt()
concat()

863

String
toLowerCase()
toString()
toUpperCase()
trim()
valueOf()

,
.
.
,
.
,
.
.


String.fromCharCode()
,
.

HTML-
JavaScript String ,
, HTML-.
ECMAScript,
HTML ,
JavaScript. ,
HTML ,
:
var s = " !";
var html = s.bold().link("JavaScript:alert('hello')").fontcolor("red");

,
:
anchor()
<a name=>.
big()
<big>.
blink()
<blink>.
bold()
<b>.
fixed()
<tt>.
fontcolor() <font color=>.
fontsize() <font size=>.
italics()
<i>.
link(url)
<a href=>.
small()
<small>.
strike()
<strike>.
sub()
<sub>.
sup()
<sup>.

JavaScript. String
. length
String . String
. ,
. :

864

JavaScript

JavaScript , String,
. , String.toUpperCase(),
, .
ECMAScript5 JavaScript, ES5,
, . ,
s, s[2] s.charAt(2). ,
for/in, ,
.

.
3

String.charAt()
n-

.charAt(n)

, .


n- .

String.charAt() n- .
. n 0 .length-1,
. : JavaScript ,
, 1.

.
String.charCodeAt(), String.indexOf(), String.lastIndexOf()

String.charCodeAt()
n-

.charCodeAt(n)

, .


n- 16- 0 65 535.

charCodeAt() charAt(), ,
, , ,

865

String.concat()

. n ,
charCodeAt() NaN.
String.from
CharCode().

.
String.charAt(), String.fromCharCode()

String.concat()

.concat(, ...)

, ...

, .


, .

concat() ( )
. .
: .
String.concat() Array.concat().
, +.

.
Array.concat()

String.fromCharCode()

String.fromCharCode(c1, c2, ...)

c1, c2, ...

,
.


, .


, . ,
fromCharCode() String()
String.

866

JavaScript

String.charCodeAt(),
.

// "hello"
var s = String.fromCharCode(104, 101, 108, 108, 111);

.
String.charCodeAt()

String.indexOf()

.indexOf()
.indexOf(, )

, .
, ,
. 0 (
) .length-1 ( ).
, .


, ,
, 1, .

String.indexOf() , ,
.
, . , String.indexOf()
.
.
, String.indexOf() 1.

.
String.charAt(), String.lastIndexOf(), String.substring()

String.lastIndexOf()
,

.lastIndexOf()
.lastIndexOf(, )

, .

String.length

867

, ,
. : 0 (
) .length-1 ( ).
, .


, ,
, 1, .

String.lastIndexOf() , ,
.
, . , String.lastIndexOf()
.
, ,
.
, String.lastIndexOf() 1.
: String.lastIndexOf() ,
.
0, .length-1.

.
String.charAt(), String.indexOf(), String.substring()

String.length

.length

String.length ,
. s
s.length-1. length for/in
delete.

String.localeCompare()

.localeCompare(_)

_
,
.

868

JavaScript


, . _, lo
caleCompare() . _,
.
, 0.

< >,
; , ,
. , ,
. , , , ch
, d.
localeCompare() ,
. ECMAScript
, ;
, ,
.

, ,
:
var strings; // ;
strings.sort(function(a,b) { return a.localeCompare(b) });

String.match()

.match(regexp)

regexp

RegExp, .
RegExp,
RegExp().


, . ,
regexp g.
.

match() ,
regexp. , g
regexp ( 10).
regexp g, match() .
, match() null.
, .
0 . ,
.

String.replace()

869


. index
. , input .
regexp g, match() ,
. null,
, , .
.
, ,
index input. : match()
,
.
RegExp.exec().

:
"1 plus 2 equals 3".match(/\d+/g) // ["1", "2", "3"]


. URL-,
, URL:
var url = /(\w+):\/\/([\w.]+)\/(\S*)/;
var text = "Visit my home page at http://www.isp.com/~david";
var result = text.match(url);
if (result != null) {
var fullurl = result[0]; // "http://www.isp.com/~david"
var protocol = result[1]; // "http"
var host = result[2]; // "www.isp.com"
var path = result[3]; // "~david"
}

.
RegExp, RegExp.exec(), RegExp.test(), String.replace(), String.search(); 10

String.replace()
( ),

.replace(regexp, )

regexp

RegExp, .
,
RegExp.
, , ,
. . .


, regexp
.

870

JavaScript

replace() .
, regexp,
. regexp g,
replace() .
.
, . ,
. ,
$ . ,
, ,
.

$1, $2, , $99

, 1 99
regexp

$&

, regexp

$`

$'

$$

ECMAScript v3 , replace()
, .
,
. , ,
, . ,
.
. ,
, ,
.

JavaScript:
text.replace(/JavaScript/i, "JavaScript");

Doe, John John Doe:


name.replace(/(\w+)\s*,\s*(\w+)/, "$2 $1");


:
text.replace(/"([^"]*)"/g, "``$1''");

:
text.replace(/\b\w+\b/g, function(word) {
return word.substring(0,1).toUpperCase() +
word.substring(1);
});

.
RegExp, RegExp.exec(), RegExp.test(), String.match(), String.search(); 10

String.search()

871

String.search()

.search(regexp)

regexp

RegExp, ,
. RegExp,
RegExp().


, regexp,
1, .

search() ,
regexp, 1,
.
, g.
regexp.lastIndex , ,
, .

var s = "JavaScript is fun";


s.search(/script/i) // 4
s.search(/a(.)a/) // 1

.
RegExp, RegExp.exec(), RegExp.test(), String.match(), String.replace(); 10

String.slice()

.slice(, )

, .
, , .
1 , 2 ..

. ,
. ,
, .


, ,
( ) ( ).

872

JavaScript

slice() , , ,
.
slice(), substring() substr() String
. slice() , substring(),
. slice() substr() ,
, substr()
. , String.slice() Array.slice().

var s = "abcdefg";
s.slice(0,4) // "abcd"
s.slice(2,4) // "cd"
s.slice(4) // "efg"
s.slice(3,-1) // "def"
s.slice(3,-2) // "de"
s.slice(-3,-1) // "ef"; IE 4 "abcdef"

Internet Explorer 4 (
Internet Explorer ).
, , 0.

.
Array.slice(), String.substring()

String.split()

.split(, )

, .
,
. ,
. ,
.


, ,
.
, .

split() ,
.
, ,
.

String.split()

873

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

split() :
"1:2:3:4:5".split(":"); // ["1","2","3","4","5"]
"|a|b|c|".split("|"); // ["", "a", "b", "c", ""]

split()
, :
var words = sentence.split(' ');

,
:
var words = sentence.split(/\s+/);

,
. ,
:
"hello".split(""); // ["h","e","l","l","o"]
"hello".split("", 3); // ["h","e","l"]

,
,
. , HTML-
:
var text = "hello <b>world</b>";
text.split(/(<[^>]*>)/); // ["hello ","<b>","world","</b>",""]

.
Array.join(), RegExp; 10

874

JavaScript

String.substr()

.substr(, )

. ,
, : 1 , 2
..
. ,
.


, , (
); , , ,
.

substr() , .
: substr()
. String.sub
string() String.splice(),
. , ECMAScript ,
, .

var s = "abcdefg";
s.substr(2,2); // "cd"
s.substr(3); // "defg"
s.substr(-3,2); // "ef"; IE 4 "ab"

IE 4 (
IE ). ,
, 0.

.
String.slice(), String.substring()

String.substring()

.substring(, )

,
.

String.toLocaleLowerCase()

875

,
. ,
.


, .
, , -1.

String.substring() ,
. ,
.
, ( 0). ,
, .
, ,
. ,
, ,
-.
:
String.slice() String.substr().
, String.substring() .

.
String.charAt(), String.indexOf(), String.lastIndexOf(), String.slice(), String.substr()

String.toLocaleLowerCase()

.toLocaleLowerCase()


,
. , ,
, ,
toLowerCase().

.
String.toLocaleUpperCase(), String.toLowerCase(), String.toUpperCase()

String.toLocaleUpperCase()

.toLocaleUpperCase()


,
. , ,

876

JavaScript

, ,
toUpperCase().

.
String.toLocaleLowerCase(), String.toLowerCase(), String.toUpperCase()

String.toLowerCase()

.toLowerCase()


,
, .

String.toString()

Object.toString()

.toString()


. .

TypeError

, ,
String.

.
String.valueOf()

String.toUpperCase()

.toUpperCase()


,
, .

String.trim()

.trim()

ECMAScript5

String.valueOf()

877


, .

.
String.replace()

String.valueOf()

Object.valueOf()

.valueOf()

TypeError

, ,
String.

.
String.toString()

SyntaxError

ObjectErrorSyntaxError

new SyntaxError()
new SyntaxError()

,
. ,
message SyntaxError.


SyntaxError. , Syntax
Error message;
,
. SyntaxError(), ( new),
, new.

message

name

,
. ,
, , .
. Error.message.
, . SyntaxError
SyntaxError.

878

JavaScript

SyntaxError
. eval(), Function() RegExp()
. .
Error.

.
Error, Error.message, Error.name

TypeError
,

ObjectErrorTypeError

new TypeError()
new TypeError()

,
. ,
message TypeError.


TypeError. , TypeError
message;
, .
TypeError(), ( new),
, new.

message ,
. , ,
, . .
Error.message.
name
, . TypeError
TypeError.

TypeError , ,
. null
. ,
, , ,
- , new ,
-. JavaScript
TypeError,
, .
Error.

.
Error, Error.message, Error.name

undefined

879

undefined

undefined

undefined , undefined.
,
. undefined for/in
delete. undefined
, .
, (undefined),
===, == undefined
null.

unescape()

unescape(s)


s.

unescape() , ,
escape(). s
%xx %uxxxx ( x
) \u00xx \uxxxx.
unescape() ECMA
Script, ECMA
Scriptv3. ECMAScript ,
. decodeURI() decodeURICompo
nent(). . escape().

.
decodeURI(), decodeURIComponent(), escape(), String

URIError
URI

new URIError()
new URIError()

ObjectErrorURIError

880

JavaScript

,
. ,
message URIError.


URIError. , URIError
message;
, .
URIError(), ( new),
, new.

message

name

,
. ,
, , .
. Error.message.
, . URIError
URIError.

URIError decodeURI() decodeURIComponent(),



. encodeURI()
encodeURIComponent(),
.
Error.

.
Error, Error.message, Error.name

IV
IV.

JavaScript

JavaScript.
JavaScript,
Window, Document, Element, Event, XMLHttpRequest, Storage, Canvas File.
jQuery.
, ,
, , ,
.

,
( ),
.

ApplicationCache

EventTarget

Node

ArrayBuffer

FieldSet

NodeList

ArrayBufferView

File

Option

Attr

FileError

Output

Audio

FileReader

PageTransitionEvent

BeforeUnloadEvent

FileReaderSync

PopStateEvent

Blob

Form

ProcessingInstruction

BlobBuilder

FormControl

Progress

Button

FormData

ProgressEvent

Canvas

FormValidity

Screen

CanvasGradient

Geocoordinates

Script

CanvasPattern

Geolocation

Select

CanvasRenderingContext2D

GeolocationError

Storage

ClientRect

Geoposition

StorageEvent

CloseEvent

HashChangeEvent

Style

Comment

History

Table

Console

HTMLCollection

TableCell

ConsoleCommandLine

HTMLFormControlsCollection

TableRow

CSSRule

HTMLOptionsCollection

TableSection

CSSStyleDeclaration

IFrame

Text

CSSStyleSheet

Image

TextArea

DataTransfer

ImageData

TextMetrics

DataView

Input

TimeRanges

Document

jQuery

TypedArray

DocumentFragment

Label

URL

DocumentType

Link

Video

DOMException

Location

WebSocket

DOMImplementation

MediaElement

Window

DOMSettableTokenList

MediaError

Worker

DOMTokenList

MessageChannel

WorkerGlobalScope

Element

MessageEvent

WorkerLocation

ErrorEvent

MessagePort

WorkerNavigator

Event

Meter

XMLHttpRequest

EventSource

Navigator

XMLHttpRequestUpload

JavaScript

ApplicationCache

EventTarget

ApplicationCache applicationCache Window.


API .
API:
( )
, 20.4. ,
,
, , .
20.4.2.

status.
unsigned short UNCACHED = 0
manifest: .
unsigned short IDLE = 1
, .
unsigned short CHECKING = 2
.
unsigned short DOWNLOADING = 3
, .
unsigned short UPDATEREADY = 4
.
unsigned short OBSOLETE = 5
.

readonly unsigned short status


.
, .

void swapCache()
status UPDATEREADY,
: ,

884

JavaScript

, ,
. swap
Cache(), ,
. ,
,
, Location.reload().
void update()

, .
- ,
.



ApplicationCache .
ApplicationCache
EventTarget, ApplicationCache.
Event. progress
ProgressEvent, ,
.
oncached
, .
.
onchecking
,
.
, .
ondownloading , ,
, ..
, .
progress.
onerror
, .
, ,

.
onnoupdate
, ,
.
.
onobsolete
,
. .
.
onprogress
,
.
ProgressEvent.
onupdateready ,
(
). .

ArrayBuffer

885

ArrayBuffer

ArrayBuffer
, .
ArrayBufferView,
.

new ArrayBuffer(unsigned long length)


ArrayBuffer .
ArrayBuffer 0.

readonly unsigned long byteLength


ArrayBuffer.

ArrayBufferView
, ArrayBuffer
ArrayBufferView ,
ArrayBuffer. ArrayBufferView
: , ,
DataView.

readonly ArrayBuffer buffer


ArrayBuffer, .
readonly unsigned long byteLength
, .
readonly unsigned long byteOffset
,
.

Attr

Attr Element. Attr
attributes Node getAttributeNode()
getAttributeNodeNS() Element.
,
Attr.
Element.getAttribute() Element.set
Attribute().
Attr.

readonly string localName


, .

886

JavaScript

readonly string name


, , .
readonly string namespaceURI
URI, , null,
.
readonly string prefix
null, .
string value
.

Audio
HTML- <audio>

Node, Element, MediaElement

Audio, HTML- <audio>. Audio ,


, , ,
MediaElement.

new Audio([string src])


<audio> preload,
auto. src,
src.

BeforeUnloadEvent
Event

Event

unload Window ,
; -
.
unload BeforeUnloadEvent.
,
Window.confirm().
returnValue .
.
Event Window.

string returnValue
,
. ,
.

Blob
,
Blob
. Blob
, ,
. Blob , .

BlobBuilder

887

Blob MIME-
,
Blob.
Blob : FileReader
Blob, BlobBuilder
Blob. XMLHttpRequest
Blob. Blob ,
, 22.6.

readonly unsigned long size


Blob .
readonly string type
MIME- Blob, , .

Blob slice(unsigned long start, unsigned long length, [string contentType])


Blob, length
Blob, start. contentType,
, type Blob

BlobBuilder
Blob
BlobBuilder Blob
ArrayBuffer Blob.
Blob, BlobBuilder,
append() getBlob().

new BlobBuilder()
BlobBuilder BlobBuilder()
.

void append(string text, [string endings])


Blob text UTF-8.
void append(Blob data)
Blob
data.
void append(ArrayBuffer data)
Blob data
ArrayBuffer.
Blob getBlob([string contentType])
Blob, ,
BlobBuilder .
Blob. contentType,
type Blob.

888

JavaScript

, type Blob
.

Button
HTML- <button>

Node, Element, FormControl

Button HTML- <button>.


Button FormControl Element. ,
type Button ( FormControl)
submit, , ,
, ,
Button ( FormControl).

, <button> type
submit.
string formAction
HTML- formaction. ,
, action .
string formEnctype
HTML- formenctype. ,
, enctype
.
string formMethod
HTML- formmethod. ,
, method .
string formNoValidate
HTML- formnovalidate. ,
, noValidate .
string formTarget
HTML- formtarget. ,
, target .

Canvas
HTML-

Node, Element

Canvas HTML- <canvas>.


, API .
width height,
toDataUrl() ,
, getCon
text(). CanvasRenderingContext2D.

unsigned long height


unsigned long width
width height <canvas>
. width
300, height 150.

Canvas

889

<canvas>
style, width height .
( )
( )
.

object getContext(string contextId, [ ...])


,
Canvas. 2d, CanvasRenderingContext2D,
.
.
<canvas> CanvasRenderingCon
text2D, .. getContext("2d")
.
HTML5 2d
.
, WebGL, . ,
, webgl, ,
.
, , , Canvas
RenderingContext2D.
string toDataURL([string type], [ ...])
toDataURL() URL-
data://, <img> .
:
// <img>
var canvas = document.getElementById("my_canvas");
var image = document.createElement("img");
image.src = canvas.toDataURL();
document.body.appendChild(image);

type , MIME-
. ,
image/png. PNG ,
.
, PNG, ,
. , type image/
jpeg, 0 1,
.
.

toDataURL() <canvas>,
. , <canvas>
, (
drawImage() , CanvasPattern),
, .
, , <canvas> ,
-,
.

890

JavaScript

CanvasGradient
Canvas
CanvasGradient ,
strokeStyle fillStyle CanvasRenderingContext2D. CanvasGra
dient createLinearGradient() createRadialGradient()
CanvasRenderingContext2D.
CanvasGradient addColorStop()
,
. ,
.
, .

void addColorStop(double offset, string color)


addColorStop() .
color CSS. offset
0.0 1.0,
. 0
, 1 .
,
.
, .
, .
, .
,
.

CanvasPattern

CanvasPattern createPattern() CanvasRendering
Context2D. CanvasPattern
strokeStyle fillStyle CanvasRenderingContext2D.

CanvasRenderingContext2D
,
CanvasRenderingContext2D
.
. 21.4,
Canvas, CanvasGradient, CanvasPattern, ImageData TextMetrics.


Canvas

, .
. Canvas
.

CanvasRenderingContext2D

891


.
Canvas .

. :
, ,
.
,
.
moveTo();
, .
, , ,
Canvas .
: lineTo()
, rect() , arc() arcTo() ,
bezierCurveTo() quadraticCurveTo() .
,
stroke(),
fill(); .

. ,
.
clip() , ,
.
,
fill() clip() , ()
, .
, closePath().
, ( ) ,
isPointInPath().
,
.
, ,
, . , ,
, ,
,
. fill() clip().

,
,
,
fillStyle strokeStyle.
CSS, CanvasGradient CanvasPat
tern, .
createLinearGradient() createRadialGradient(),
createPattern().
CSS #RRGGBB, RR,
GG BB ,
(red), (green) (blue) 00 FF. ,

892

JavaScript

- #FF0000.
, rgba(R, G, B, A).
R, G B ,
0 255, A - (
), 0.0 (
) 1.0 ( ). , -
rgba(255, 0, 0, 0.5).

,
Canvas ,
.
lineWidth, lineCap,
lineJoin.


strokeRect() fill
Rect(). , clearRect() .


API Canvas Image,
HTML- <img> ,
Image() ( . Image).
, -
<canvas> <video>.
Canvas drawImage(),

.


fillText() , strokeText() ,
. font;
CSS.
X ,
textAlign,
Y textBaseline.


(0,0),
, X ,
Y . width height <canvas>
X Y,
.
,
, .
translate(), scale() rotate(),
.
, ,
, lineTo(), .
API Canvas ,
.

893

CanvasRenderingContext2D

CanvasRenderingContext2D
. shadowColor,
shadowOffsetX shadowOffsetY. , sha
dowBlur .


, ,
.
, , globalCompositeOperation,
. ,
, .
.
,
, . ,
.
S (source) , D (des
tination) , R (result) , s ( ) , d -
:

"copy"

R=S

"destination-atop" R = (1-d)S + sD .
,
.
"destination-in"

R = sD


, .

"destination-out"

R = (1-s)D

,
, ,
.
.

"destination-over" R = (1-d)S + D

,
.

"lighter"

R=S+D


, ,
.

"source-atop"

R = dS + (1-s)D ,
.
.

"source-in"

R = dS


. .
,
.

"source-out"

R = (1-d)S

,
, ,
.
.

894

JavaScript

"source-over"

R = S + (1-s)D

.
,
.

globalCompositeOperation.

"xor"

R = (1-d)S + (1-s)D ,
.
,
. , ,
,
.


save() restore()
CanvasRenderingContext2D. save() ,
restore()
.
CanvasRenderingContext2D (
canvas, ).
, .


getImageData() , putImage
Data() .
, JavaScript.

readonly Canvas canvas


Canvas, .
any fillStyle
, , .
CanvasGradient CanvasPattern.

string font
, .
,
CSS- font. : 10px sans-serif.
, em ex,
, , larger, smal
ler, bolder lighter,
CSS- <canvas>.
double globalAlpha
,
, . -
, , .
0.0 ( ) 1.0 ( :
).

CanvasRenderingContext2D

895

string globalCompositeOperation
() .

globalAlpha. : source-over.
destination-over copy.
. ,
-
: , .
21.4.13.
string lineCap
, .
.
. : butt.

"butt"

. ,
.
. .

"round"

,
, ;
.

"square"

, .
butt,

.

string lineJoin
, / ,
lineJoin , .
.
, miter, ,
, .
,
.
miterLimit.
, .
round , , ,
, .
bevel , , ,
.
double lineWidth
. 1.

.
double miterLimit
lineJoin
miter,
.

896

JavaScript

. miterLimit
.
. 10, ,
5
. , .
double shadowBlur
. 0;
. ,
. ,
.
string shadowColor
CSS.
.
double shadowOffsetX
double shadowOffsetY
.
, .
: 0.
.
any strokeStyle
, , .
CSS
CanvasGradient CanvasPattern.
string textAlign
X,
fillText() strokeText().
left, center, right, start end. start end
dir ( ) <canvas>. start.
string textBaseline
Y,
fillText() strokeText().
top, middle, bottom, alphabetic, hanging ideographic.
alphabetic.

void arc(double x,y,radius,startAngle,endAngle, [boolean anticlockwise])



.
. ,
. . ,
, .. X,
0. .
(true)
(false).

.

897

CanvasRenderingContext2D

void arcTo(double x1, y1, x2, y2, radius)


,
,
. x1 y1 P1, x2
y2 P2. , ,
radius. ,
P1,
, P1 P2.
.
,
.
, P1 P2.
100 100 (
), c :
c.beginPath();
c.moveTo(150, 100); //
c.arcTo(200,100,200,200,40); //
c.arcTo(200,200,100,200,30); //
//
c.arcTo(100,200,100,100,20); //
c.arcTo(100,100,200,100,10); //
c.closePath(); //
c.stroke(); //

void beginPath()
beginPath()
. beginPath() .

beginPath().
void bezierCurveTo(double cp1x, cp1y,cp2x, cp2y, x, y)
bezierCurveTo()
. ,
x y.
(cpX1, cpY1) (cpX2, cpY2).
(x, y).
void clearRect(double x, y, width, height)
clearRect()
. rect(),
.
void clip()

.
, .
, save(),
restore() .
.
fill(), clip()

.

898

JavaScript

void closePath()
, closePath()
, .
( moveTo()) .
fill() clip() ,
closePath() ,
.
ImageData createImageData(ImageData imagedata)
ImageData , data.
ImageData createImageData(double w, double h)
ImageData .
ImageData
( - 0).
w h CSS-.
CSS- .
width height ImageData
,
w h.
CanvasGradient createLinearGradient(double x0, y0, x1, y1)
CanvasGradient,
.
: .
addColorStop() .
,
CanvasGradient strokeStyle fillStyle.
CanvasPattern createPattern(Element image, string repetition)
CanvasPattern ,
. image <img>, <canvas>
<video>, , .
repetition , .
:

"repeat"

.
.

"repeat-x"

X.

"repeat-y"

Y.

"no-repeat"

, .

,
CanvasPattern strokeStyle fillStyle.
CanvasGradient createRadialGradient(double x0, y0, r0, x1, y1, r1)
CanvasGradient,
.
: .
addColorStop() .

CanvasRenderingContext2D

899

, Can
vasGradient strokeStyle fillStyle.
0
, 1
(, , -
) .
void drawImage(Element image, double dx, dy, [dw, dh])
image (
<img>, <canvas> <video>) ,
(dx, dy). dw dh,
, dw dh
.
void drawImage(Element image, double sx, sy, sw, sh, dx, dy, dw, dh)
drawImage()
image . image
<img>, <canvas> <video>. (sx,sy)
, sw sh
. ,
CSS-
. ,
:
drawImage() . ,
, ,
.
void fill()
fill() ,
, fillStyle.
, closePath(). (
: , .)
.
fill() stroke() .

, fill()
, , .
, ,
,
,
.
void fillRect(double x, y, width, height)
fillRect() ,
, fillStyle.
rect(), fillRect()
.
void fillText(string text, double x, y, [double maxWidth])
fillText() text, font fill
Style. x y , ,
textAlign textBaseline,
.

900

JavaScript

textAlign left start ( ),


( ),
end ,
X. textAlign center,
X.
( textAlign right, end
start ) X.
textBaseline alphabetic ( ), bottom
ideographic,
Y. textBaseline center,
Y.
textBaseline top hanging,
Y.
maxWidth .
text , maxWidth,
.
ImageData getImageData(double sx, sy, sw, sh)

.
ImageData .
- ,
ImageData.
RGB . -
, ImageData
( ).
CSS- ,
width height ImageData
sw sh.
Canvas.toDataURL(),
. getImageData() ImageData,
;
. ,
, (
drawImage() , CanvasPattern),
,
. , , <canvas> ,
-,
.
boolean isPointInPath(double x, y)
isPointInPath() true,
; false.
,
. x 0
canvas.width, y 0 canvas.height.
, isPointInPath() ,
, :
() ,
. ,

CanvasRenderingContext2D

901

.
, width
height (, style.width style.height),
,
. ,
onclick <canvas>
:
// onclick <canvas>. , .
function hittest(event) {
var canvas = this; //
var c = canvas.getContext("2d"); //
//
var bb = canvas.getBoundingClientRect();
//
var x = (event.clientX-bb.left)*(canvas.width/bb.width);
var y = (event.clientY-bb.top)*(canvas.height/bb.height);
// ,
if (c.isPointInPath(x,y)) c.fill();
}

void lineTo(double x, double y)


lineTo() .
(x,y).
, (x,y).
TextMetrics measureText(string text)
measureText() text,
font, TextMetrics,
.
, width,
.
void moveTo(double x, double y)
moveTo() (x,y)
. ,
,
.
void putImageData(ImageData imagedata, double dx, dy, [sx, sy, sw, sh])
putImageData() ImageData .
,
globalCompositeOperation globalAlpha, ,
, .
dx dy .
imagedata , .

.

ImageData.
. , ImageData

902

JavaScript

. ,
ImageData, .
sx sy .
ImageData
. ( getImageData())

putImageData().
void quadraticCurveTo(double cpx, cpy, x, y)
.
,
x y. , ,
(cpX, cpY).
(x,y). bezierCurveTo().
void rect(double x, y, w, h)
.
, .
(x,y).
:
c.moveTo(x,y);
c.lineTo(x+w, y);
c.lineTo(x+w, y+h);
c.lineTo(x, y+h);
c.closePath();

void restore()

CanvasRenderingContext2D,
. . save().
void rotate(double angle)
,
, ,
. <canvas>.
: .
, Math.PI 180.
void save()
save()
. -
restore().
CanvasRendering
Context2D ( canvas),
, rotate(),
scale() translate(). , ,
clip(). ,
.
void scale(double sx, double sy)
scale()
.
. , 2.0 0.5,

CanvasRenderingContext2D

903

, ,
scale(). sx
Y, sy
X.
void setTransform(double a, b, c, d, e, f)
,
translate(), scale() rotate().
:
x' a c e x = ax + cy + e
y' = b d f y = bx + dy + f
1 0 0 1 1

void stroke()
stroke() , .
, ,
strokeStyle, lineWidth,
lineCap, lineJoin miterLimit.
stroke ()
. . stroke(), fill()
.
void strokeRect(double x, y, w, h)
( )
.
strokeStyle lineWidth.
lineJoin.
rect(), strokeRect()
.
void strokeText(string text, double x, y, [maxWidth])
strokeText() fillText(), ,

fillStyle, ,
strokeStyle. strokeText()
,
fillText().
void transform(double a, b, c, d, e, f)
T
33:
a c e
b d f
0 0 1

transform() T
:
CTM' = CTM T

transform()
, . ,
transform(1,0,0,1,dx,dy). trans
form(sx, 0, 0, sy, 0, 0). x:
transform(cos(x),sin(x),-sin(x), cos(x), 0, 0)

904

JavaScript

X k,
transform(1,0,k,1,0,0). Y
transform(1,k,0,1,0,0).
void translate(double x, double y)
translate()
. x y
, .

ClientRect
,
ClientRect Window
. ,
, getBoundingClientRect() Element.
ClientRect :
.

readonly float bottom


Y .
readonly float height
. IE 8
; bottom-top.
readonly float left
X .
readonly float right
X .
readonly float top
Y .
readonly float width
. IE 8
; right-left.

CloseEvent
, -

Event

WebSocket, WebSocket
close,
CloseEvent.

readonly boolean wasClean


WebSocket ,
-, ,
, , true.
false, - .

Comment

905

Comment
HTML- XML-

Node

Comment HTML- XML-.


(.. <!-- -->) data
nodeValue, Node. Comment
Document.createComment().

string data
.
readonly unsigned long length
.

void appendData(string data)


void deleteData(unsigned long offset, unsigned long count)
void insertData(unsigned long offset, string data)
void replaceData(unsigned long offset, unsigned long count, string data)
string substringData(unsigned long offset, unsigned long count)
Comment Text,
, Text. ,
Text.

Console

( , -
, Firebug) console,
Console. API
, (
, Developer Tools ( )
Web Inspector (-).
, API
Console, Firebug Firefox -
Firebug,
. console.log()
,
. , console ,
, , Console,
, .
. ConsoleCommandLine.

void assert(any expression, string message)


message , expression
false , null, undefined, 0
.

906

JavaScript

void count([string title])


title
.
void debug(any message...)
console.log(), ,
.
void dir(any object)
,

.
void dirxml(any node)
XML HTML .
void error(any message...)
console.log(), .
void group(any message...)
message log(),
.
,
groupEnd().
void groupCollapsed(any message...)
, ,
.
void groupEnd()
,
group() groupCollapsed().
void info(any message...)
console.log(),
.
void log(string format, any message...)
. , format
, %,
, .
, , ,
.

printf() C. message
format, %s,
%d, %i, %f %o,
( message,
format). ,
%s, . ,
%d %i, .
%f ,
%o , .
void profile([string title])
JavaScript title.

ConsoleCommandLine

907

void profileEnd()

.
void time(string name)
name.
void timeEnd(string name)
name ,
time().
void trace()
.
void warn(any message...)
console.log(), .

ConsoleCommandLine

- JavaScript ( ,
, (Developer Tools) - (Web
Inspector),
JavaScript.
JavaScript
, .
. Console.

readonly Element $0
, .
readonly Element $1
, $0.

void cd(Window frame)


, cd()

frame.
void clear()
.
void dir(object o)
o.
Console.dir().
void dirxml(Element elt)
XML HTML elt. Console.
dirxml().
Element $(string id)
document.getElementById().

908

JavaScript

NodeList $$(string selector)


, , ,
CSS- selector. document.querySelec
torAll(). , NodeList.
void inspect(any object, [string tabname])
object,
. ,
, object.
: html, css, script dom.
string[] keys(any object)
object.
void monitorEvents(Element object, [string type])
type, object.
type : mouse, key, text, load,
form, drag contextmenu. type ,
object.
void profile(string title)
. Conso
le.profile().
void profileEnd()
. Console.profileEnd().
void unmonitorEvents(Element object, [string type])
type object.
any[] values(any object)
object.

CSS2Properties
. CSSStyleDeclaration

CSSRule
CSS

CSSRule CSS-
CSSStyleSheet: ,
. selectorText
, style
CSSStyleDeclaration, ,
.
CSSRule ,
, CSS Object Model.
, , CSSRule
CSSStyleRule.
.
IE 8 CSSRule selectorText
style.

CSSStyleDeclaration

909

unsigned short STYLE_RULE = 1


unsigned short IMPORT_RULE = 3
unsigned short MEDIA_RULE = 4
unsigned short FONT_FACE_RULE = 5
unsigned short PAGE_RULE = 6
unsigned short NAMESPACE_RULE = 10
type, ,
. type - , 1,
CSSRule , .

string cssText
CSS-.
readonly CSSRule parentRule
, , .
readonly CSSStyleSheet parentStyleSheet
, .
string selectorText
type STYLE_RULE,
, , .
readonly CSSStyleDeclaration style
type STYLE_RULE, ,
, selectorText.
: style
, CSSStyleDeclaration, ,
.
readonly unsigned short type
. ,
.

CSSStyleDeclaration
CSS-
CSSStyleDeclaration CSS- ,
, ,
CSS-. style HTMLElement
CSSStyleDeclaration style CSSRule.
Window.getComputedStyle() CSSStyleDeclaration,
.
CSSStyleDeclaration CSS-
. CSS-
, JavaScript.
, ,
font-family, , , ,
: fontFamily. , float
float, cssFloat.

910

JavaScript

, CSS, .

, , CSSStyleDeclaration
:
string cssText
.
, CSS,
, .
readonly unsigned long length
/, CSSStyleDecla
ration. CSSStyleDeclaration , ,
CSS- .

CSSStyleSheet
CSS
CSS.
, , ,
CSSRule. CSSStyleSheet, ,
styleSheets[] Document
sheet <style> <link>,
.
IE 8 cssRules[] rules[],
insertRule() deleteRule() addRule() removeRule().

readonly CSSRule[] cssRules


, ,
CSSRule, . IE
rules.
boolean disabled
true ,
. false
.
readonly string href
URL- , , null,
.
readonly string media
, .

, ,
appendMedium() deleteMedium(). (
MediaList,
.)

DataTransfer

911

readonly Node ownerNode


, , null,
. . Link Style.
readonly CSSRule ownerRule
CSSRule ( ),
, null,
- . ( , CSSRule
@import.)
readonly CSSStyleSheet parentStyleSheet
, , null,
.
readonly string title
, .
title <style> <link>, .
readonly string type
MIME- . CSS text/css.

void deleteRule(unsigned long index)


index cssRules. IE 8
removeRule().
unsigned long insertRule(string rule, unsigned long index)
( ) CSS- (,
) index cssRules
. IE 8
addRule() , (
) , index
.

DataTransfer

(drag-and-drop),
( , )
.
, dataTransfer (. Event),
DataTransfer. DataTransfer
: ,
. , DataTransfer
,
,
.
API Microsoft
IE , , .
HTML5 API, IE.
, HTML5 API,
items, , ,
DataTransferItem.

912

JavaScript

API, , ,
. ,
() .
API 17.7.

string dropEffect
, .
: none, copy, move link.
, -
dragenter dragover.
, ,
.
string effectAllowed

: , .
dragstart.
: none ( ), copy (), copyLink (
), copyMove ( ), link (
), linkMove ( ), move () all
(). ( , , ,
.)
readonly File[] files
,
, , File.
readonly string[] types
, , , MIME , DataTransfer ( set
Data(), , -
, ). , ,
, contains()
.
, indexOf().

void addElement(Element element)


element,
,
. ,
- .
void clearData([string format])
format, setData().
string getData(string format)
format. format
text ( ),
text/plain. url (
), text/uri-list.
drop .

DataView

913

void setData(string format, string data)


data MIME- format.
dragstart
. -
. ,
,
.
void setDragImage(Element image, long x, long y)
image ( <img>),
. x y
.
, dragstart.

DataView
/ ArrayBuffer

ArrayBufferView

DataView ArrayBufferView, ArrayBuffer (


ArrayBuffer) / 1-, 2- 4-
, 4- 8- .
(big-endian) (little-endian)
. . TypedArray.

new DataView(ArrayBuffer buffer, [unsigned long byteOffset], [unsigned long byteLength])


DataView,
.
.
, byteOffset
. byte
Length, byteOffset.

ArrayBuffer,
DataView.
. ,
, littleEndian.
false, (big-endian)
,
. true, (littleendian) .
float getFloat32(unsigned long byteOffset, [boolean littleEndian])
4 , byteOffset,
.
double getFloat64(unsigned long byteOffset, [boolean littleEndian])
8 , byteOffset,
.
short getInt16(unsigned long byteOffset, [boolean littleEndian])
2 , byteOffset,
.

914

JavaScript

long getInt32(unsigned long byteOffset, [boolean littleEndian])


4 , byteOffset,
.
byte getInt8(unsigned long byteOffset)
byteOffset,
.
unsigned short getUint16(unsigned long byteOffset,[boolean littleEndian])
2 , byteOffset,
.
unsigned long getUint32(unsigned long byteOffset, [boolean littleEndian])
4 , byteOffset,
.
unsigned byte getUint8(unsigned long byteOffset)
byteOffset,
.
void setFloat32(unsigned long byteOffset, float value, [boolean littleEndian])
value 4-
, byteOffset.
void setFloat64(unsigned long byteOffset, double value, [boolean littleEndian])
value 8-
, byteOffset.
void setInt16(unsigned long byteOffset, short value, [boolean littleEndian])
value 2-
, byteOffset.
void setInt32(unsigned long byteOffset, long value, [boolean littleEndian])
value 4-
, byteOffset.
void setInt8(unsigned long byteOffset, byte value)
value 1-
, byteOffset.
void setUint16(unsigned long byteOffset, unsigned short value,[boolean littleEndian])
value 2-
, byteOffset.
void setUint32(unsigned long byteOffset, unsigned long value, [boolean littleEndian])
value 4-
, byteOffset.
void setUint8(unsigned long byteOffset, octet value)
value 1-
byteOffset.

Document
HTML- XML-

Node

Document Node, . do
cumentElement Element . Docu
ment ( Comment DocumentType),

Document

915

Element,
.
Document document
Window. Document contentDocument
IFrame ownerDocument Node.
Document
, .
Document ,
.
, .
Document, Element, ,
. , Event
Target, .
Document createDocment() createHTML
Document() DOMImplementation:
document.implementation.createHTMLDocument("New Doc");

, HTML- XML-
Document. . responseXML XMLHttpRequest.
HTMLDocument, ,
. ,
, , ,
HTML- XML-.

, ,
name <iframe>, <form> <img>.
Element NodeList
. <iframe> Window
<iframe>. 15.2.2.
readonly Element activeElement
, .
Element body
HTML- <body>. (
, <frameset>,
<frameset>.)
readonly string characterSet
.
string charset
. characterSet,
, .
readonly string compatMode
BackCompat,
.
CSS1Compat.
string cookie
, , cookies,
. Cookies

916

JavaScript

, -.
, ,
,
. cookies -,
cookies. JavaScript
cookies, . ,
/,
, .
20.2.
readonly string defaultCharset
.
readonly Window defaultView
Window , .
string designMode
on,
. off,
. (
contenteditable.)
15.10.4.
string dir
HTML- dir <html>.
, documentElement.dir.
readonly DocumentType doctype
DocumentType, <!DOCTYPE> .
readonly Element documentElement
. HTML-
Element, <html>.
childNodes[], Node,
. . body.
string domain
, , null,
.

. 13.6.2.1.
readonly HTMLCollection embeds
, , <embed>,
.
readonly HTMLCollection forms
, , Form,
.
readonly Element head
HTML- <head>.
readonly HTMLCollection images
, , Image,
.

Document

917

readonly DOMImplementation implementation


DOMImplementation .
readonly string lastModified
.
HTTP- Last-Modified, -
.
readonly HTMLCollection links
, , ,
. HTMLCollection <a> <area>,
href, <link>. . Link.
readonly Location location
Window.location.
readonly HTMLCollection plugins
embeds.
readonly string readyState
loading, ,
complete . comp
lete, readystatechange Document.
readonly string referrer
URL- , , null,
, -
, .
HTTP- referer. :
r, JavaScript- .
readonly HTMLCollection scripts
, , <script>,
.
readonly CSSStyleSheet[] styleSheets
, ,
, . HTML-
, <link> <style>.
string title
<title> .
readonly string URL
URL- . locati
on.href. (
location.hash), location URL URL-.
Document.URL Window.URL.

Node adoptNode(Node node)


node ,
, ownerDocument ,
.
importNode() , .

918

JavaScript

void close()
, open(),
.
Comment createComment(string data)
Comment .
DocumentFragment createDocumentFragment()
DocumentFragment.
Element createElement(string localName)
Element . HTML .
Element createElementNS(string namespace, string qualifiedName)
Element.
URI ,
, .
Event createEvent(string eventInterface)
Event
. , Event,
UIEvent, MouseEvent, MessageEvent .
Event , ,
, initEvent(), initUIEvent(),
initMouseEvent() .
,
Event.initEvent().
dispatchEvent() Event
Target. false isTrusted.
ProcessingInstruction createProcessingInstruction(string target, string data)
ProcessingInstruction target data.
Text createTextNode(string data)
Text, text.
Element elementFromPoint(float x, float y)
Element
(x, y).
boolean execCommand(string commandId, [boolean showUI, [string value]])
commandId
, .
HTML5 :
bold insertLineBreak selectAll
createLink insertOrderedList subscript
delete insertUnorderedList superscript
formatBlock insertParagraph undo
forwardDelete insertText unlink
insertImage italic unselect
insertHTML redo

( createLink) value.
execCommand() false,
.

Document

919

. execCommand()
15.10.4.
Element getElementById(string elementId)
Element id,
elementId, .
, null. id
,
elementId, .
, .. Element,
. :
Id, ID.
NodeList getElementsByClassName(string classNames)
, , , class
, classNames. class
Names ,
. NodeList ,
.
NodeList ,
. , Element.
NodeList getElementsByName(string elementName)
, , ,
elementName name.
, NodeList 0 length.
NodeList getElementsByTagName(string qualifiedName)
, ,
Element , , ,
. NodeList
, .. ,
.
HTML-
. , * .
: Element ,
.
NodeList getElementsByTagNameNS(string namespace, string localName)
, getElementsByTagName(),
URI
.
boolean hasFocus()
true, (,
,
).
Node importNode(Node node, boolean deep)
, , ,
. deep true,
.
. ownerDocument
, parentNode null,

920

JavaScript

. ,
, . . adoptNode().
Window open(string url, string name, string features, [boolean replace])
open() ,
open() Window. . Window.
Document open([string type], [string replace])

( Document,
). open() write()
writeln(), , close(),
.
15.10.2.
HTML-, type
text/html.
. replace true,
.
,
, ..
.
boolean queryCommandEnabled(string commandId)
true, commandId
execCommand(), false . ,
undo, . 15.10.4.
boolean queryCommandIndeterm(string commandId)
true, commandId , queryCommand
State() - . ,
HTML5, ,
, , . 15.10.4.
boolean queryCommandState(string commandId)
commandId. ,
bold italic, true,
, , false
. ,
false. 15.10.4.
boolean queryCommandSupported(string commandId)
true, , false
. 15.10.4.
string queryCommandValue(string commandId)
.
15.10.4.
Element querySelector(string selectors)
, CSS-
selectors ( CSS- ,
).
NodeList querySelectorAll(string selectors)
, , Element
, selectors (

DocumentFragment

921

CSS- , ).
NodeList, getElementsByTagName()
, NodeList, ,
, ,
.
void write(string text...)
text .
<script>
open(). 15.10.2.
void writeln(string text...)
HTMLDocument.write() ,
, , ,
<pre>.

Document ,
, , Document,
. Document
, Element. Element,
Document EventTarget.
Document .
readyState, readystatechange.
onreadystate
change. , DOMContentLoaded (17.4),
(
).
EventTarget, Document
onDOMContentLoaded.

DocumentFragment

Node

DocumentFragment () .
, ,
. DocumentFragment
, parentNode null.
DocumentFragment :
DocumentFragment , Document
Fragment, . DocumentFragment
, .
DocumentFragment Document.create
DocumentFragment().
DocumentFragment query
Selector() querySelectorAll(), ,
Document.

Element querySelector(string selectors)


. Document.querySelector().

922

JavaScript

NodeList querySelectorAll(string selectors)


. Document.querySelectorAll().

DocumentType
<!DOCTYPE>

Node

<!DOCTYPE> .
doctype Document DocumentType .
DocumentType , .
DocumentType Document
DOMImplementation.createDocument(). DocumentType
DOMImplementation.createDocumentType().

readonly string name


. ,
<!DOCTYPE>
. HTML- html.
readonly string publicId
DTD , .
readonly string systemId
DTD , .

DOMException
, Web API
JavaScript
DOMException, .
code name . ,
DOMException
.
DOMException Error JavaScript,
, message
Error.

unsigned
unsigned
unsigned
unsigned
unsigned
unsigned
unsigned
unsigned
unsigned
unsigned
unsigned
unsigned
unsigned

short
short
short
short
short
short
short
short
short
short
short
short
short

INDEX_SIZE_ERR = 1
HIERARCHY_REQUEST_ERR = 3
WRONG_DOCUMENT_ERR = 4
INVALID_CHARACTER_ERR = 5
NO_MODIFICATION_ALLOWED_ERR = 7
NOT_FOUND_ERR = 8
NOT_SUPPORTED_ERR = 9
INVALID_STATE_ERR = 11
SYNTAX_ERR = 12
INVALID_MODIFICATION_ERR = 13
NAMESPACE_ERR = 14
INVALID_ACCESS_ERR = 15
TYPE_MISMATCH_ERR = 17

DOMImplementation

923

unsigned short SECURITY_ERR = 18


unsigned short NETWORK_ERR = 19
unsigned short ABORT_ERR = 20
unsigned short URL_MISMATCH_ERR = 21
unsigned short QUOTA_EXCEEDED_ERR = 22
unsigned short TIMEOUT_ERR = 23
unsigned short DATA_CLONE_ERR = 25
code.
,

unsigned short code


, , .
string name
. , ,
.

DOMImplementation
DOM
DOMImplementation , -
Document, DOM.
DOMImplementation implementation
Document.

Document createDocument(string namespace, string qualifiedName, DocumentType doctype)


Document XML-.
qualifiedName,
documentElement. qualifiedName
,
URI, .
doctype , null, ownerDocument
DocumentType , DocumentType
.
DocumentType createDocumentType(string qualifiedName, publicId, systemId)
DocumentType, <!DOCTYPE>,
createDocument().
Document createHTMLDocument(string title)
HTMLDocument ,
. documentElement
<html>, <head>
<body>. <head> <title>
, title.

DOMSettableTokenList

DOMTokenList

DOMSettableTokenList DOMTokenList,
value, .

924

JavaScript

classList Element DOMTokenList,


className .
classList ,
className. sandbox IFrame .
HTML-, ,
HTML5,
DOMTokenList.
DOMSettableTokenList, ,
,
. htmlFor Output audio Video
DOMSettableTokenList.

string value
,
.
.
: DOMSettableTokenList ,
, .
DOMSettableTokenList, .

DOMTokenList
,
DOMTokenList ,
, , className Element. DOMTo
kenList, , , ,
, length,
. , contains(), add(), remove()
toggle(), .
DOMTokenList ,
, .
classList Element, HTML5,
DOMTokenList , .
DOMTokenList,
. . DOMSettableTokenList.

readonly unsigned long length


DOMTokenList , ;
, .

void add(string token)


DOMTokenList token,
.
boolean contains(string token)
true, DOMTokenList token, false
.

Element

925

string item(unsigned long index)


null, index
. DOMTokenList
, .
void remove(string token)
DOMTokenList token, .
.
boolean toggle(string token)
DOMTokenList token, . .

Element

Node, EventTarget

Element HTML- XML-. tagName


. HTML-
JavaScript- Element. , XML-
HTML-,
getAttribute() setAttribute(). Element ,
Node. ,
,
children, firstElementChild, nextElementSibling .
Element .
documentElement Document
, <html> HTML-. HTML-
head body <head> <body>
. id,
Document.getElementById(). 15.2,
Element getElementsByTagName(),
getElementsByClassName() querySelectorAll(). , Document.cre
ateElement() Element .
-
, Element .
, Element EventTarget (
EventTarget),
.
HTMLElement, ,
. ,
, , ,
HTML- XML-.

, , HTML- HTML-
Element. HTML-
.
readonly Attr[] attributes
, , Attr, HTML XML- . Element
, JavaScript-,
attributes[].

926

JavaScript

readonly unsigned long childElementCount


( ),
.
readonly HTMLCollection children
, , (
, Element, Text Comment).
readonly DOMTokenList classList
class ,
.
, ,
.
DOMTokenList.
string className
class . JavaScript class
, className,
class. , 1
, class .
readonly long clientHeight
readonly long clientWidth
(document.documentElement),
, ..
, ,
.
.
readonly long clientLeft
readonly long clientTop

.
,
, .
CSSStyleDeclaration currentStyle
, IE,
CSS-, . IE 8
Window.getComputedStyle().
readonly object dataset
HTML- ,
, data-. dataset
.
.
.
data-x, dataset x, dataset.x
, getAttribute("data-x").
dataset

. delete ,
for/in .
1

. . .

Element

927

readonly Element firstElementChild


firstChild Node, Text
Comment Element.
string id
id.
id.
string innerHTML
, HTML
XML, ,
.
HTML- XML-.
HTML- XML-
.
readonly boolean isContentEditable
true, ,
false .
contenteditable ,
designMode Document.
string lang
lang, .
readonly Element lastElementChild
lastChild Node, Text
Comment Element.
readonly string localName
.
tagName,
, ( HTML-
).
readonly string namespaceURI
URL-, .
null , http://www.w3.org/1999/
xhtml.
readonly Element nextElementSibling
nextSibling Node,
Text Comment Element.
readonly long offsetHeight
readonly long offsetWidth
,
, .
readonly long offsetLeft
readonly long offsetTop
X Y CSS-
offsetParent.
readonly Element offsetParent
, ,
offsetLeft offsetTop.

928

JavaScript

offsetParent <body>.
,
offsetParent
, , offsetParent
<td>, <th> <table>.
15.8.5.
string outerHTML
HTML XML, .
, (
) HTML XML-.
readonly string prefix
.
null. XML-,
.
readonly Element previousElementSibling
previousSibling Node,
Text Comment Element.
readonly long scrollHeight
readonly long scrollWidth
.
(, CSS- overflow),
offsetHeight offsetWidth,
.
long scrollLeft
long scrollTop
, .
,
, , CSS- overflow auto. <html> (.
Document.documentElement)
. :
<iframe>. ,
. 15.8.5.
readonly CSSStyleDeclaration style
style, CSS- .
: , ,
CSS- .
. CSSStyleDeclaration.
readonly string tagName
. HTML-
, ..
<p> tagName P. XML-
, ,
. ,
nodeName Node.
string title
title .
.

Element

929

void blur()
body Document.
void click()
.
- (, ),
.
click .
void focus()
.
string getAttribute(string qualifiedName)
getAttribute()
null, . , ,
HTML-, JavaScript-,
HTML-,
. HTML-
.
XML-
, . XML-
, , ,
getAttributeNS() getAttributeNodeNS().
string getAttributeNS(string namespace, string localName)
, getAttribute(), ,
URI ,
.
ClientRect getBoundingClientRect()
ClientRect, ,
.
ClientRect[] getClientRects()
, , ClientRects,
, .
( , ,
,
.)
NodeList getElementsByClassName(string classNames)
, , ,
class classNames.
classNames
, . NodeList
.
NodeList ,
. , Document.
NodeList getElementsByTagName(string qualifiedName)
Node
List Element,
. NodeList ,

930

JavaScript

. ,
Document getElementsByTagName(),
, , ,
.
NodeList getElementsByTagNameNS(string namespace, string localName)
getElementsByTagName(), ,
URI
.
boolean hasAttribute(string qualifiedName)
true, , false
. HTML-
.
boolean hasAttributeNS(string namespace, string localName)
, hasAttribute(), ,
URI
.
void insertAdjacentHTML(string position, string text)
HTML text position
. position :
position
beforebegin

afterend

afterbegin

beforeend

Element querySelector(string selectors)


, CSS- selec
tors ( CSS- ,
).
NodeList querySelectorAll(string selectors)
, , ,
, selectors (
CSS- , ).
NodeList, getElementsByTagName(),
NodeList, , :
, .
void removeAttribute(string qualifiedName)
.
. HTML-
.
void removeAttributeNS(string namespace, string localName)
removeAttributeNS() , removeAttribute(),
, URI
.

Element

931

void scrollIntoView([boolean top])


HTML- ,
, . top
,
. true ,
,
. false, ,
. ,
, Input, focus()
. . scrollTo()
Window.
void setAttribute(string qualifiedName, string value)
.
, . HTML
. : HTML- JavaScript-
, HTML-,
HTMLElement.
.
void setAttributeNS(string namespace, string qualifiedName, string value)
, setAttribute(), ,
URI
, ,
.


Element, HTML-,
.
,
( ).
,
EventTarget.
Document
Window. ,
, Document Window. Window
,
, , Window .
,
HTML- <body>, Window, ,
, , <body> . .
Window.
, , HTML-
. ,
, .
, HTML5,
<audio> <video>, , Media
Element. , HTML5,
FormControl.

932

JavaScript

, ...

onabort

onblur*

onchange

(
, )

onclick

oncontextmenu ,

ondblclick

ondrag

( -)

ondragend

( -)

ondragenter

( )

ondragleave

(
-)

ondragover

( -)

ondragstart

( -
)

ondrop

( -)

onerror*

( )

onfocus*

oninput

( ,
onchange)

onkeydown

onkeypress

onkeyup

onload*

(, <img>)

onmousedown

onmousemove

onmouseout

onmouseover

onmouseup

onmousewheel

onreset

onscroll*

onselect

onsubmit

HTML-
HTML-:

933

Element

<audio>

Audio

<output>

Output

<button>, <input
type="button">

Button

<progress>

Progress

<canvas>

Canvas

<script>

Script

<fieldset>

FieldSet

<select>

Select

<form>

Form

<style>

Style

<iframe>

Iframe

<td>

TableCell

<img>

Image

<tr>

TableRow

<input>

Input

<tbody>, <tfoot>, <thead> TableSection

<label>

Label

<table>

Table

<a>, <area>, <link>

Link

<textarea>

TextArea

<meter>

Meter

<video>

Video

<option>

Option

HTML-, ,
, HTML- .
, HTML-
Element:

accessKey

class

CSS-: . className classList .

contentEditable .
contextMenu

id <menu>,
.
IE.

dir

: ltr ( ) rtl ( ).

draggable

, ,
- API .

dropzone

, ,
- API .

hidden

, ,
.

id

lang

spellcheck

style

CSS . . style .

tabIndex

title

934

JavaScript

HTML- , , :
<abbr> <code> <footer> <hr> <rt> <sup>
<address> <datalist> <h1> <i> <ruby> <tbody>
<article> <dd> <h2> <kbd> <s> <tfoot>
<aside> <dfn> <h3> <legend> <samp> <thead>
<b> <div> <h4> <mark> <section> <title>
<bdi> <dl> <h5> <nav> <small> <tr>
<bdo> <dt> <h6> <noscript> <span> <ul>
<br> <em> <head> <p> <strong> <var>
<caption> <figcaption> <header> <pre> <sub> <wbr>
<cite> <figure> <hgroup> <rp> <summary>

HTML- .
, ,
, . ,
, :

<a>

href, target, ping, rel, media, hreflang, type

<area>

alt, coords, shape, href, target, ping, rel, media, hreflang, type

<audio>

src, preload, autoplay, loop, controls

<base>

href, target

<blockquote> cite
<body>

onafterprint, onbeforeprint, onbeforeunload, onblur, onerror, onfocus, onhash


change, onload, onmessage, onoffline, ononline, onpagehide, onpageshow,
onpopstate, onredo, onresize, onscroll, onstorage, onundo, onunload

<button>

autofocus, disabled, form, formaction, formenctype, formmethod, formnova


lidate, formtarget, name, type, value

<canvas>

width, height

<col>

span

<colgroup>

span

<command>

type, label, icon, disabled, checked, radiogroup

<del>

cite, datetime

<details>

open

<embed>

src, type, width, height

<fieldset>

disabled, form, name

<form>

accept-charset, action, autocomplete, enctype, method, name, novalidate, target

<html>

manifest

<iframe>

src, srcdoc, name, sandbox, seamless, width, height

<img>

alt, src, usemap, ismap, width, height

<input>

accept, alt, autocomplete, autofocus, checked, dirname, disabled, form, form


action, formenctype, formmethod, formnovalidate, formtarget, height, list,
max, maxlength, min, multiple, name, pattern, placeholder, readonly, required,
size, src, step, type, value, width

<ins>

cite, datetime

935

ErrorEvent

<keygen>

autofocus, challenge, disabled, form, keytype, name

<label>

form, for

<li>

value

<link>

href, rel, media, hreflang, type, sizes

<map>

name

<menu>

type, label

<meta>

name, http-equiv, content, charset

<meter>

value, min, max, low, high, optimum, form

<object>

data, type, name, usemap, form, width, height

<ol>

reversed, start

<optgroup>

disabled, label

<option>

disabled, label, selected, value

<output>

for, form, name

<param>

name, value

<progress>

value, max, form

<q>

cite

<script>

src, async, defer, type, charset

<select>

autofocus, disabled, form, multiple, name, required, size

<source>

src, type, media

<style>

media, type, scoped

<table>

summary

<td>

colspan, rowspan, headers

<textarea>

autofocus, cols, disabled, form, maxlength, name, placeholder, readonly, requi


red, rows, wrap

<th>

colspan, rowspan, headers, scope

<time>

datetime, pubdate

<track>

default, kind, label, src, srclang

<video>

src, poster, preload, autoplay, loop, controls, width, height

ErrorEvent

Event

, Worker,
, onerror
WorkerGlobalScope, error
Worker. ErrorEvent,
. preventDefault() ErrorEvent
( false )

.

936

JavaScript

readonly string filename


URL- JavaScript,
.
readonly unsigned long lineno
, .
readonly string message
.

Event
, IE jQuery
, Event,
, ,
. Event
.
, IE, 8 ,
.
, ,
IE, ,
jQuery, IE.
17, jQuery
19.4.

, : , ,
MouseEvent , ,
KeyEvent ,
. , MouseEvent KeyEvent,
Event. IE jQuery ,
Element, Event. Event,
, -
, .

, Element (
Document Window).

, ,
, . HTML5
,
, .
,
. . BeforeUnloadEvent, CloseEvent, ErrorEvent, HashChangeEvent,
MessageEvent, PageTransitionEvent, PopStateEvent, ProgressEvent StorageEvent.
Event.
, HTML5,

Event. Event,
. , ,
Event.

Event

937

, MessageEvent, ,
load Window playing MediaElement.

eventPhase.
, IE.
unsigned short CAPTURING_PHASE = 1

.
unsigned short AT_TARGET = 2

unsigned short BUBBLING_PHASE = 3

.

Event ,
, .
, IE jQuery.
, , Event
, ,
.
readonly boolean altKey
, Alt .
, IE.
readonly boolean bubbles*
true, (
stopPropagation()), false . IE.
readonly unsigned short button
, mouse
down, mouseup click. 0 , 2
1 . ,
,
, , ,
mousemove. ,
:
. ,
.
IE button.
: 1 ,
, 2 4
() . jQuery
button IE, which.
readonly boolean cancelable*
true, ,
, preventDefault(), false
.
IE.

938

JavaScript

boolean cancelBubble
IE,
,
true.
stopPropagation().
readonly integer charCode
keypress
.
. keydown keyup.
String.fromCharCode(). key
press keyCode.
Firefox keyCode keypress,
charCode.
, IE jQuery.
readonly long clientX
readonly long clientY
X Y
. :
; , clientY
0 , .
, IE,
. . pageX pageY.
readonly boolean ctrlKey
, Ctrl .
, IE.
readonly EventTarget currentTarget*
Element, Document Window, .
target.
IE, jQuery.
readonly DataTransfer dataTransfer
(drag-and-drop) DataTrans
fer, .
; , ,
clientX, clientY ,
. dragstart, drag dragend
-; dragenter, dragover, dragleave drop
-.
DataTransfer 17.7.
readonly boolean defaultPrevented*
true, defaultPrevented(), false
. ,
. ( jQuery
isDefaultPrevented(), .)
readonly long detail
(). click, mousedown mouseup
: 1 , 2
, 3 .. Firefox
DOMMouseScroll, .

Event

939

readonly unsigned short eventPhase*


.
, . IE.
readonly boolean isTrusted*
true, , false
, JavaScript.
,
.
readonly Element fromElement
mouseover mouseout IE fromElement
, .
relatedTarget.
readonly integer keyCode
.
. ,
, . , ,
.
, ,
,
17.8. ,
, IE.
readonly boolean metaKey
, , Meta,
. ,
IE.
readonly integer offsetX, offsetY
IE ,
, - (.
srcElement). .
readonly integer pageX, pageY
,
clientX clientY,
. IE, jQuery
.
readonly EventTarget relatedTarget*
( ),
. mouseover ,
. mouse
out , ,
. IE,
jQuery. . fromElement toElement,
IE.
boolean returnValue
IE ,
-, ,
false.
preventDefault().

940

JavaScript

readonly long screenX, screenY



. ,

, IE.
readonly boolean shiftKey
, Shift .
, IE.
readonly EventTarget srcElement
IE ,
.
target.
readonly EventTarget target*
, .. , . (
, ,
EventTarget.) IE,
jQuery. C. srcElement.
readonly unsigned long timeStamp*
, , ,
.
, Date().
Firefox 4 ,
.
IE. jQuery
, Date.getTime().
Element toElement
mouseover mouseout IE
, .
relatedTarget.
readonly string type*
, Event. ,
, ,
on. , click, load submit.
, IE.
readonly Window view
( (view)),
.
, .
IE.
readonly integer wheelDelta

Y. ;
17.6. ,
, IE 8 .
readonly integer wheelDeltaX
readonly integer wheelDeltaY
, ,
X Y. ,

Event

941

, 17.6. wheelDeltaY,
, wheelDelta.
readonly integer which
, ,
IE, jQuery.
, button: 1 , 2
3 .
, keyCode.

Event,
Event.
void initEvent(string type, boolean bubbles, boolean cancelable)
type, bubbles cancelable Event.
createEvent() Document,
Event.
, EventTarget,
dispatchEvent() . (
type, bubbles cancelable) .
,
, createEvent() ( Mouse
Event)
, initMouseEvent() ( ).
void preventDefault()
-,
, .
, .
IE, jQuery.
IE false
returnValue.
void stopImmediatePropagation()
stopPropagation(), , ,
, .
,
.
IE, jQuery.
void stopPropagation()

.
,
. IE,
jQuery. IE stopPropagation()
true cancelBubble.


, , DOM Level3
Events.
, ( ) .
,

942

JavaScript

,
.
readonly unsigned short buttons
button, IE
.
readonly string char
(..
), .
readonly string data
textinput .
readonly unsigned long deltaMode

deltaX, deltaY deltaZ.
: DOM_DELTA_PIXEL, DOM_DELTA_LINE, DOM_DELTA_PAGE.

-
.
readonly long deltaX, deltaY, deltaZ

.
readonly unsigned long inputMethod
textinput .
: DOM_INPUT_METHOD_UNKNOWN, DOM_INPUT_
METHOD_KEYBOARD, DOM_INPUT_METHOD_PASTE, DOM_INPUT_METHOD_DROP, DOM_INPUT_METHOD_IME,
DOM_INPUT_METHOD_OPTION, DOM_INPUT_METHOD_HANDWRITING, DOM_INPUT_METHOD_VOICE, DOM_
INPUT_METHOD_MULTIMODAL, DOM_INPUT_METHOD_SCRIPT.
readonly string key
, ,
, char. ,
, ( , Tab Down).
readonly string locale
textinput
(, en-GB), ,
.
readonly unsigned long location

. : DOM_KEY_LOCATION_
STANDARD, DOM_KEY_LOCATION_LEFT, DOM_KEY_LOCATION_RIGHT, DOM_KEY_LOCATION_NUMPAD, DOM_
KEY_LOCATION_MOBILE, DOM_KEY_LOCATION_JOYSTICK.
readonly boolean repeat
true,
,
.


, ,
,
.

EventSource

943

boolean getModifierState(string modifier)


true,
-
modifier, false . modifier
: Alt, AltGraph, CapsLock, Control, Fn, Meta, NumLock,
Scroll, Shift, SymbolLock Win.

EventSource
Comet- HTTP-

EventTarget

EventSource HTTP-,
- .
, Server-Sent Events, URL EventSource()
message EventSource.
Server-Sent Events
.

new EventSource(string url)


EventSource, -,
url. url URL- .

readyState.
unsigned short CONNECTING = 0
, EventSource
.
unsigned short OPEN = 1
.
unsigned short CLOSED = 2
close(),
, .

readonly unsigned short readyState


. ,
.
readonly string url
URL-, EventSource.

void close()
. EventSource
. ,
EventSource.

944

JavaScript


, EventSource
,
.
Event
Target. , EventSource,
EventSource. , ,
.
onerror
.
Event.
onmessage .
MessageEvent, , ,
data .
onopen
.
Event.

EventTarget
,
, , ,
,
. ,
on , , ,
.
. 17.2 , IE
8 , ;
.

void addEventListener(string type,function listener,[boolean useCapture])


listener type.
type on. useCapture
true, (17.2.3)
, . ,

, , ,
false.
boolean dispatchEvent(Event event)
event.
, Event document.create
Event() ( Events, ).
Event:
initEvent() (. Event).
, .
Event isTrusted.
, , false.

. ,
. ,

FieldSet

945

, ,
Event,
.
void removeEventListener(string type, function listener, [boolean useCapture])
listener .
, addEventListener().

Internet Explorer
IE 8 addEventListener() removeEventListener().
, . (
17.2.4.)
void attachEvent(string type, function listener)
listener type.
, , type on.
void detachEvent(string type, function listener)
attachEvent().

FieldSet
<fieldset> HTML-

Node, Element, FormControl

FieldSet <fieldset> HTML- <form>.


FieldSet , FormControl.

boolean disabled
true, FieldSet .
FieldSet .
readonly HTMLFormControlsCollection elements
, , ,
<fieldset>.

File

Blob

File Blob. File , ,


. .
files <input type=file>
files DataTransfer, Event,
drop.
File,
, , 22.7.

, .
FormData
File XMLHttpRequest.send(), File
. ,
FileReader ( Blob).

946

JavaScript

readonly Date lastModifiedDate


null, .
readonly string name
( ).

FileError
,
FileError ,
FileReader FileReaderSync.
, FileError.
FileError
error FileReader.
, FileWriter (
22.7, ,
) .

FileError:
unsigned short NOT_FOUND_ERR = 1
. (, ,
, , .)
unsigned short SECURITY_ERR = 2
, ,
.
unsigned short ABORT_ERR = 3
.
unsigned short NOT_READABLE_ERR = 4
, ,
.
unsigned short ENCODING_ERR = 5
readAsDataURL() ,
, URL- data://.

readonly unsigned short code


.
, .

FileReader
File Blob

EventTarget

FileReader
File Blob. ,
:
FileReader FileReader().

FileReader

947

.
File Blob .
, onload,
result. , onerror, error
FileError, .

FileReader .
,
, FileReaderSync.

new FileReader()
FileReader FileReader(),
.

readyState:
unsigned short EMPTY = 0
.
unsigned short LOADING = 1
.
unsigned short DONE = 2
, .

readonly FileError error


,
FileError, .
readonly unsigned short readyState
FileReader.
, .
readonly any result
,
File Blob ArrayBuffer (
). readyState
LOADING progress,
File Blob.
, null.

void abort()
. readyState DONE,
result null error FileError
code, FileError.ABORT_ERR.
abort loadend.

948

JavaScript

void readAsArrayBuffer(Blob blob)


blob result
ArrayBuffer.
void readAsBinaryString(Blob blob)
blob,
result.
0 255.
String.charCodeAt(). ,
:
ArrayBuffer, .
void readAsDataURL(Blob blob)
blob, (
Blob) URL- data:// result.
void readAsText(Blob blob, [string encoding])
blob,
encoding
result. encoding ,
UTF-8 ( UTF-16
, Byte Order Mark).


, FileRe
ader .
, , EventTarget,
FileReader.
FileReader FileReader.
, .
FileReader ProgressEvent.
loadstart,
progress, load loadend.
loadstart, progress,
error abort loadend.
onabort
, abort().
onerror
, - . error FileReader
FileError, code .
onload
File
Blob. result FileReader File Blob
, .
onloadend
FileReader
load, error abort. ,
FileReader loadend ,
.

FileReaderSync

949

onloadstart
,
- .
onprogress
20 ,
File Blob. ProgressEvent
, result FileReader
.

FileReaderSync
File Blob
FileReaderSync FileReader,
, Worker.
, :
FileReaderSync() ,
File Blob, FileError.

new FileReaderSync()
FileReaderSync FileReaderSync(),
.

FileError,
- .
ArrayBuffer readAsArrayBuffer(Blob blob)
blob ArrayBuffer.
string readAsBinaryString(Blob blob)
blob, (String.fromChar
Code()) .
string readAsDataURL(Blob blob)
blob, type blob
URL- data:// .
string readAsText(Blob blob, [string encoding])
blob,
encoding ( UTF-8 UTF-16, enco
ding ) .

Form
<form> HTML-

Node, Element

Form <form> HTML-. elements


HTMLCollection, .
submit() reset()
, .
document.forms[].
(, , ..) Form.elements,

950

JavaScript

.
Form.
, Input phone name
f JavaScript- f.phone.
HTML- 15.9. ,
FormControl,
FieldSet, Input, Label, Select TextArea.
,
HTML5,
.

, , HTML-
.
string acceptCharset
,
.
string action
URL-, .
string autocomplete
on off. on,
,
.
readonly HTMLFormControlsCollection elements
, , .
string enctype
.
:
application/x-www-form-urlencoded ( )
multipart/form-data
text/plain
readonly long length
, elements.
, , ,
, f n f[n]
f.elements[n].
string method
HTTP- URL- action.
get post.
string name
, HTML- name.
,
Form.
boolean noValidate
true, .
HTML- novalidate.

FormControl

951

string target
, ,
.

boolean checkValidity()
, ,
. true,
. -
, invalid
false.
void dispatchFormChange()
formchange .
,
change, .
void dispatchFormInput()
forminput .
,
input, .
void reset()
.
void submit()
, submit.


, ,
Element, , Form.
onreset
,
. , false
.
onsubmit
.
, false .

FormControl

HTML- <input>,
<button>, <select> <textarea>.
. HTML-
15.9,
Form, Input, Select TextArea.
<fieldset> <output> , , ,
. FieldSet Output
FormControl, .

952

JavaScript

(
), HTML5,
.

boolean autofocus
true,
. ( FieldSet Output .)
boolean disabled
true, .
.
( Output ; FieldSet
, .)
readonly Form form
Form, , null,
. <form>,
. ,
HTML- form, id <form>,
.
readonly NodeList labels
, , Label,
. ( FieldSet .)
string name
HTML- name .
Form:
.
.
string type
<input> type type
text, type <input>. <button>, <select>
<textarea> type button, select-one ( select-multip
le, multiple) textarea, .
<fieldset> type fieldset, <output>
output.
readonly string validationMessage
,
.
, ,
.
readonly FormValidity validity
,
, .
string value
value,
.
, . HTML-
value. Output textContent,
Node. FieldSet .

953

FormData

readonly boolean willValidate


true, ,
false .


.
EventTarget,
:

onformchange

change,
formchange
.
.

onforminput

input,
forminput
.
.

oninvalid

,
, invalid.
, ,
.

boolean checkValidity()
true, (
). invalid
false.
void setCustomValidity(string error)
error ,

error ,
. error , error
, .

FormData
HTTP- multipart/form-data
FormData XMLHttpRequest Level2 (XHR2),
multipart/form-data HTTP-
PUT XMLHttpRequest.
, , File.
FormData /
append(). ,
, FormData send()
XMLHttpRequest.

954

JavaScript

new FormData()
, , FormData.

void append(string name, any value)


FormData name value.
value Blob (, File
Blob).

FormValidity

validity FormControl FormValidity,
.
valid false,
, (
), true.
, HTML5,
.

readonly boolean customError


FormControl.setCustomValidity() .
readonly boolean patternMismatch
.
readonly boolean rangeOverflow
.
readonly boolean rangeUnderflow
.
readonly boolean stepMismatch
.
readonly boolean tooLong
.
readonly boolean typeMismatch
.
readonly boolean valid
true,
false.
false, , ,
true.
readonly boolean valueMissing
, .

Geocoordinates

955

Geocoordinates

.

readonly double accuracy


( latitude longitude) .
readonly double altitude
null, .
readonly double altitudeAccuracy
( altitude) .
altitude null, altitudeAccuracy
null.
readonly double heading

null, .
, ( speed) ,
heading NaN.
readonly double latitude
.
readonly double longitude

.
readonly double speed
null,
.
. . heading.

Geolocation

Geolocation ,
. ,
, Geolocation Navigator,
navigator.geolocation. , ,
:
Geoposition, GeolocationError.

void clearWatch(long watchId)


. watchId
,
watchPosition().
void getCurrentPosition(function success, [function error], [object options])

options ( option ).
, ,

956

JavaScript

success Geoposition.
( - ,
) error
GeolocationError.
long watchPosition(function success, [function error], [object options])
getCurrentPosition(),

success , .
, clearWatch(),
.

options, getCurrentPosition() watchPosition(),


, :
boolean enableHighAccuracy

, .
false. ,
WiFi GPS,
true GPS.
long maximumAge
(),
, Geoposition success.
0, .. getCurrentPosition()
watchPosition() .
60000, ,
Geoposition, .
long timeout

. Infinity.
error.
,
timeout.

GeolocationError
,

, error Geolocation
Error, .

code:
unsigned short PERMISSION_DENIED = 1
.
unsigned short POSITION_UNAVAILABLE = 2
.
, , .

Geoposition

957

unsigned short TIMEOUT = 3



(. timeout Geolocation).

readonly unsigned short code


, .
readonly string message
, .
.

Geoposition

Geoposition
. :
Geocoordinates, .

readonly Geocoordinates coords


Geocoordinates,
, .
readonly unsigned long timestamp
, .
Date.

HashChangeEvent
, hashchange

Event

hashchange ,
( URL-, #) .
hash Location
Back () For
ward (). hashchange.
HashChangeEvent.
, location.hash
hashchange 22.2.

readonly string newURL


location.href. ,
URL-, .
readonly string oldURL
location.href.

958

JavaScript

History
Window
History .
History
URL-. History
.

readonly long length


URL- ()
. ,
.

void back()
back() ,
History, URL- ( ),
. ,
Back . :
history.go(-1);

void forward()
forward() ,
History, URL- ( ),
. ,
Forward . :
history.go(1);

void go([long delta])


History.go()
URL-,
.
, . history.go(-1)
history.back() ,
Back. 0
.
void pushState(any data, string title, [string url])
,
(. 22)
data, title url.
,
, popstate
PopStateEvent
data state.
title ,
. (
).
url,
,

HTMLCollection

959

. url
document location. url
URL-, ,
. URL-
, #.
void replaceState(any data, string title, [string url])
pushState(), ,
,
data, title url.

HTMLCollection
HTML-,
HTMLCollection , ,
Element ,
name id . Document
HTMLCollection, forms image.
HTMLCollection item() namedItem()
,
: HTMLCollection
. :
document.images[0] // HTMLCollection
document.forms.address // HTMLCollection

readonly unsigned long length


.

Element item(unsigned long index)


, index, null,
index . ,
( ).
object namedItem(string name)
, name id
name null, .
, .

HTMLDocument
. Document

HTMLElement
. Element

HTMLFormControlsCollection
, ,

HTMLCollection

HTMLFormControlsCollection HTMLCol
lection, Form

960

JavaScript

. HTMLCollection, ,
, , name id
. HTML- (
), name,
HTMLFormControlsCollection , HTMLCollection.
HTMLFormControlsCollection,
, HTMLFormControlsCollection
, , ,
. , , ,
value, value
. ,
.

HTMLOptionsCollection
Option

HTMLCollection

HTMLOptionsCollection HTMLCollection,
Option, Select.
namedItem(),
Option, ,
. HTMLOptionsCollection
length,
.

unsigned long length


. , length
HTMLCollection, .
, Option
, Option, ,
Select. length ,
Select <option/>.
long selectedIndex
Option 1,
Option . ,
.

void add(Element option, [any before])


option ( <option> <optgroup>)
( Select), ,
before. before null,
. before ,
,
. before Element, option
.
Element item(unsigned long index)
HTMLOptionsCollection HTMLCollection.
index null, .

IFrame

961

,
.
object namedItem(string name)
Option , name
id name. ,
null. ,
. Option,
. ,
NodeList . ,
HTMLOptionsCollection ,
name , .
void remove(long index)
<option> index.
, ,
.

IFrame
HTML- <iframe>

Node, Element

IFrame <iframe> HTML-.


<iframe> getElementById() ,
IFrame. , <iframe>
frames Window <iframe>
, Window, <iframe>.

readonly Document contentDocument


, <iframe>.
<iframe> , -
, (13.6.2).
readonly Window contentWindow
Window, <iframe>. ( frameElement
Window IFrame.)
string height
<iframe> CSS-.
height.
string name
<iframe>. name,
target Link Form.
readonly DOMSettableTokenList sandbox
HTML5- sandbox
.
sandbox ,
, <iframe>.
sandbox , ,
<iframe> ,
,
location , . sandbox

962

JavaScript

, ,
. : allow-same-origin, allow-scripts, al
low-forms allow-top-navigation.
sandbox
. HTML.
boolean seamless
seamless. true,
<iframe> ,
. ,
CSS .
seamless HTML5
.
string src
src <iframe>: URL-
.
string srcdoc
srcdoc
<iframe> . srcdoc HTML5
.
string width
CSS-. width.

Image
<img> HTML-

Node, Element

Image HTML- <img>. ,


, document.images[].
src Image .
, ,
. ,
. 21.1.
Image,
<img> document.createElement() Image().
: ,
; , src
Image. ,
Image .

new Image([unsigned long width, unsigned long height])


HTML-, Image
document.createElement().
JavaScript Image(),
. width / height,
width height <img>.

, , Image
, HTML- alt, usemap, ismap.

ImageData

963

readonly boolean complete


true, src
, false.
unsigned long height
CSS-,
.
.
readonly unsigned long naturalHeight
.
readonly unsigned long naturalWidth
.
string src
URL- .
. Image
, .
unsigned long width
CSS-,
.
.

ImageData
<canvas>
ImageData , ,
. Image
Data createImageData() getImageData() CanvasRen
deringContext2D <canvas>.
width height .
data , .
data[] .
, R, G, B A, .
, (x,y)
ImageData :
var
var
var
var
var

offset = (x + y*image.width) * 4;
red = image.data[offset];
green = image.data[offset+1];
blue = image.data[offset+2];
alpha = image.data[offset+3];

data[] , ,

0 255. , length
. i ImageData
i.data.length i.width * i.height * 4.

readonly byte[] data


, , , ,
, .

964

JavaScript

readonly unsigned long height


data.
readonly unsigned long width
, data.

Input
HTML- <input>

Node, Element, FormControl

Input HTML- <input>.


type: Input , ,
, , , .
<input> , Input
. HTML-
15.9. ,
Input ( type, value, name form) FormControl.

, , Input
, Element FormControl. ,
, , HTML5,
.
string accept
type file, MIME-
, , ,
. audio/*, video/* image/*.
accept.
string autocomplete
true,
Input , .
autocomplete. . autocomplete Form.
boolean checked
,
.
.
boolean defaultChecked

checked, . , checked
. checked.
string defaultValue

, . ,
. value.
readonly File[] files
, type file,
, ,
File, , .

Input

965

string formAction*
,
action . formaction.
string formEnctype*
,
enctype . formenctype.
string formMethod*
,
method . formmethod.
boolean formNoValidate*
,
noValidate . formno
validate.
string formTarget*
,
target . formtarget.
boolean indeterminate
,
(.. , ).
- HTML-:
JavaScript.
readonly Element list*
<datalist>, <option>,
.
string max*
Input.
long maxLength
type text password,
,
. size. maxlength.
string min*
Input.
boolean multiple*
true,
. multiple.
string pattern*
, ,
.
JavaScript ( ),
, , RegExp.
,
, - . (
^ $.)
pattern.

966

JavaScript

string placeholder
, Input,
. ,
.
placeholder.
boolean readOnly
true, .
readonly.
boolean required*
true, ,
Input.
required.
readonly Option selectedOption*
list multiple false,
Option list, .
unsigned long selectionEnd
,
. . setSelectionRange().
unsigned long selectionStart

<textarea>. . setSelectionRange().
unsigned long size

. size. maxLength.
string step*
( )
. any
. step.
Date valueAsDate*
(. FormControl) Date.
double valueAsNumber*
(. FormControl) .

, , Input
Element FormControl. , ,
, HTML5,
.
void select()
, Input.
,
.
void setSelectionRange(unsigned long start, unsigned long end)
, Input,
start ( ) end.

jQuery

967

void stepDown([long n])*


, step, n
.
void stepUp([long n])*
, step,
n .

jQuery

jQuery 1.4

jQuery

jQuery.
19.
, .
. sel
jQuery. idx
. elt elts
, , . f
, ,
, jQuery
. .
, ,
, .
,
. , ,
jQuery, .

jQuery
jQuery
, jQuery.
jQuery() , ,
jQuery,
( Document). $ jQuery,
, , jQuery() $():
jQuery(sel [, context=document])
jQuery, ,
context sel.
jQuery(elts)
jQuery, .
elts ,
, ( NodeList jQuery),
.
jQuery(html, [props])
html HTML
jQuery, ,
. html HTML-,
props , HTML-
.

968

JavaScript

jQuery(f)
f , ,
.
, f ,
document. jQuery,
document.

jQuery
jQuery CSS3
19.8.1.
:
, id
* tagname .classname #id


A
A
A
A

B B - A
> B B - A
+ B B - , A
~ B B - A


[attr]
[attr=val] val
[attr!=val] val
[attr^=val] val
[attr$=val] val
[attr*=val] val
[attr~=val] val
[attr|=val] val


:button :header :password :submit
:checkbox :image :radio :text
:file :input :reset


:animated :disabled :hidden :visible
:checked :enabled :selected


:eq(n) :first :last :nth(n)
:even :gt(n) :lt(n) :odd


:first-child :nth-child(n)
:last-child :nth-child(even)
:only-child :nth-child(odd)
:nth-child(xn+y)


:contains(text) :not(selector)
:empty :parent
:has(selector)

jQuery

969

jQuery
jQuery.
,
. 19.1.2.
context
, , .
$() Document.
each(f(idx,elt))
f .
, false. jQuery,
.
get(idx):elt
get():array
jQuery.

. get() , toArray().
index():int
index(sel):int
index(elt):int

.
, sel, 1,
.
elt 1,
.
is(sel):boolean
true, sel
.
length
.
map(f(idx,elt)):jQuery
f
jQuery, ,
null undefined .
selector
, $().
size():int
length.
toArray():array
.

jQuery
, , ,
,
. jQuery 1.4
jQuery

970

JavaScript

, .
19.8.2.
add(sel, [context])
add(elts)
add(html)
add() $(),
.
andSelf()
( ).
children([sel])
, ,
. .
.
closest(sel, [context])
,
sel, context.
context , context jQuery.
contents()
,
.
end()
,
, .
eq(idx)
. jQuery 1.4
.
filter(sel)
filter(elts)
filter(f(idx):boolean)
,
, sel,
elts, , - f true,
.
find(sel)
,
sel.
first()
.
has(sel)
has(elt)
, ,
, sel
elt.
last()
.

jQuery

971

next([sel])
.
sel, ,
.
nextAll([sel])
, .
sel, ,
.
nextUntil(sel)
, ,
( ) , sel.
not(sel)
not(elts)
not(f(idx):boolean)
filter(). ,
, sel, elts,
f true. elts
, , . f
.
offsetParent()

.
parent([sel])
. sel,
, .
parents([sel])
. sel,
, .
parentsUntil(sel)
( )
, .
prev([sel])
.
sel, ,
.
prevAll([sel])
,
. sel, ,
.
prevUntil(sel)
, ,
( ) , sel.
pushStack(elts)
,
end(), (
, ) elts.

972

JavaScript

siblings([sel])
,
. sel, ,
sel.
slice(startidx, [endidx])
, ,
startidx ( ) endidx.
. endidx ,
length.

jQuery
, , HTML-
CSS- .
current ,
. 19.2.
addClass(names)
addClass(f(idx,current):names)
CSS- class
. f
, .
attr(name):value
attr(name, value)
attr(name, f(idx,current):value)
attr(obj)

.
value
f
. -
, ,
.
css(name):value
css(name, value)
css(name, f(idx,current):value)
css(obj)
attr(), HTML-
, CSS-.
data():obj
data(key):value
data(key, value)
data(obj)

.
.

value. -
.

jQuery

973

hasClass(name):boolean
true, -
name class.
height():int
height(h)
height(f(idx,current):int)
( , )
, h ,
f, .
innerHeight():int
.
innerWidth():int
.
offset():coords
offset(coords)
offset(f(idx,current):coords)
X Y ( )

coords , f,
.
top left.
offsetParent():jQuery

jQuery.
outerHeight([margins=false]):int
, , margins
true, .
outerWidth([margins=false]):int
, , margins
true, .
position():coords

. top left.
removeAttr(name)
.
removeClass(names)
removeClass(f(idx,current):names)
class
. ,
,
.
removeData([key])
.
, .

974

JavaScript

scrollLeft():int
scrollLeft(int)

.
scrollTop():int
scrollTop(int)

.
toggleClass(names, [add])
toggleClass(f(idx,current):names, [add])
class
. f,

. add true false,
.
val():value
val(value)
val(f(idx,current)):value


value , f,
.
width():int
width(w)
width(f(idx,current):int)
( , )
w
, f,
.

jQuery
, , ,
. , , content
jQuery, HTML ,
target jQuery,
. 19.2.5 19.3.
after(content)
after(f(idx):content)
content f
.
append(content)
append(f(idx,html):content)
content
f
.
appendTo(target):jQuery
,
target, , target .

jQuery

975

before(content)
before(f(idx):content)
after(), content
, .
clone([data=false]):jQuery

jQuery, . data
true, ( ),
.
detach([sel])
remove(), ,
.
empty()
.
html():string
html(htmlText)
html(f(idx,current):htmlText)

HTML.
htmlText ,
f, .
insertAfter(target):jQuery
,
target, , target .
insertBefore(target):jQuery
,
target, , target .
prepend(content)
prepend(f(idx,html):content)
append(), content
, .
prependTo(target):jQuery
appendTo(),
, target, .
remove([sel])
,
sel, , , (
). ,
, -
jQuery.
replaceAll(target)
,
, target, ,
target .

976

JavaScript

replaceWith(content)
replaceWith(f(idx,html):content)
content
f ,
HTML,
.
text():string
text(plainText)
text(f(idx,current):plainText)

.
plainText ,
f, .
unwrap()
,
.
wrap(wrapper)
wrap(f(idx):wrapper)
, ,
. ,
, . wrapper
, jQuery, HTML,
-.
wrapAll(wrapper)
, wrapper

- wrapper.
wrapInner(wrapper)
wrapInner(f(idx):wrapper)
wrap(), wrapper (
f) ,
.

jQuery

. 19.4.
event-type()
event-type(f(event))
f event-type
event-type. jQuery ,
:
ajaxComplete() blur() focusin() mousedown() mouseup()
ajaxError() change() focusout() mouseenter() resize()
ajaxSend() click() keydown() mouseleave() scroll()
ajaxStart() dblclick() keypress() mousemove() select()
ajaxStop() error() keyup() mouseout() submit()
ajaxSuccess() focus() load() mouseover() unload()

jQuery

977

bind(type, [data], f(event))


bind(events)
f type .
data, f.
type
.
,
-
.
delegate(sel, type, [data], f(event))
f . f
type, ,
sel .
data, f.
die(type, [f(event)])
, live(),
type , ,
.
- f, .
hover(f(event))
hover(enter(event), leave(event))
mouseenter mouseleave
. ,
.
live(type, [data], f(event))
f type.
data, f.
,
jQuery. f
, type (
document), . .
delegate().
one(type, [data], f(event))
one(events)
bind(),
.
ready(f())
f, ,
, ,
.
$(f).
toggle(f1(event), f2(event),...)
click ,
-.

978

JavaScript

trigger(type, [params])
trigger(event)
type , params
. params
.
event, type ,
,
.
triggerHandler(type, [params])
trigger(),
, .
unbind([type],[f(event)])
,
jQuery .
type
. f,
type .
type
.
undelegate()
undelegate(sel, type, [f(event)])

.
type ,
sel, .
f.

jQuery

, ,
. jQuery,
. 19.5.

complete duration easing queue specialEasing step

jQuery.fx.off
true,
.
animate(props, opts)
, CSS-,
props, , ,
opts. 19.5.2.
animate(props, [duration], [easing], [f()])
, CSS-,
props, ,
duration easing. f
.

jQuery

979

clearQueue([qname="fx"])

.
delay(duration, [qname="fx"])
duration
.
dequeue([qname="fx"])

.
.
fadeIn([duration=400],[f()])
fadeOut([duration=400],[f()])
duration
, .
f, , .
fadeTo(duration, opacity, [f()])
CSS- opacity opacity
duration. f,
, .
hide()
hide(duration, [f()])
.
,
, duration .
f, , .
slideDown([duration=400],[f()])
slideUp([duration=400],[f()])
slideToggle([duration=400],[f()])
,
, duration.
f, ,
.
show()
show(duration, [f()])
.
,
, duration
. f, ,
.
stop([clear=false], [jump=false])
(
) . clear true,
. jump
true, ,
.

980

JavaScript

toggle([show])
toggle(duration, [f()])
show true, show()
. show false,
hide() .
show , .
duration,
, duration .
f, ,
.
queue([qname="fx"]):array
queue([qname="fx"], f(next))
queue([qname="fx"], newq)

. -
f .
-
newq.

jQuery Ajax
jQuery,
Ajax, ,
. jQuery.
19.6.
Ajax
success error notmodified timeout parsererror

Ajax
text html xml script json jsonp

Ajax
ajaxStart ajaxSend ajaxSuccess ajaxError ajaxComplete ajaxStop

Ajax
async context global processData type
beforeSend data ifModified scriptCharset url
cache dataFilter jsonp success username
complete dataType jsonpCallback timeout xhr
contentType error password traditional

jQuery.ajax(options):XMLHttpRequest
, Ajax,
Ajax- jQuery.
, ,
.
19.6.3.1, 19.6.3.2.
jQuery.ajaxSetup(options)
.
options, jQuery.ajax().
,

jQuery

981

.
.
jQuery.getJSON(url, [data], [f(object,status)]):XMLHttpRequest
url, data.
JSON
f.
XMLHttpRequest, , .
jQuery.getScript(url, [f(text,status)]):XMLHttpRequest
url.
, f.
XMLHttpRequest, ,
. ,
f XMLHttpRequest.
jQuery.get(url, [data], [f(data,status,xhr)], [type]):XMLHttpRequest
HTTP GET- url, data,
, URL-.
type
Content-Type ,
. (, )
f XMLHttp
Request, . XMLHttpRequest,
, jQuery.get().
jQuery.post(url, [data], [f(data,status,xhr)], [type]):XMLHttpRequest
jQuery.get(), GET-, HTTP POST.
jQuery.param(o, [old=false]):string
o www-form-urlencoded,
URL- HTTP POST-
. Ajax jQuery
, data.
jQuery 1.3,
true.
jQuery.parseJSON(text):object
JSON
. Ajax jQuery
JSON.
load(url, [data], [f(text,status,xhr)])
url, data.
HTML
, .
f ,
f , XMLHttpRequest,
.
url ,
,
.
Ajax
jQuery, load() , .

982

JavaScript

jQuery, jQuery,
.
serialize():string

www-form-urlencoded.

jQuery
( ),
jQuery. 19.7.
jQuery.boxModel
jQuery.support.boxModel.
jQuery.browser
,
. msie Internet Explorer, mozilla Fire
fox, webkit Safari Chrome, opera Opera. version
.
jQuery.contains(a,b):boolean
true, a b.
jQuery.data(elt):data
jQuery.data(elt, key):value
jQuery.data(elt, data)
jQuery.data(elt, key, value)
data(). elt
. elt
key
. elt data
elt. elt,
key value
.
jQuery.dequeue(elt, [qname="fx"])
. , $(elt).
dequeue(qname).
jQuery.each(o, f(name,value)):o
jQuery.each(a, f(index,value)):a
f o, name
value , f value.
, ,
f ,
index value . ,
f false. .
jQuery.error(msg)
msg.
(, jQuery.error = alert).
jQuery.extend(obj):object
jQuery.extend([deep=false], target, obj...):object
obj
jQuery.

jQuery

983

, ,
target. deep true,
. ,
.
jQuery.globalEval(code):void
code JavaScript
<script>. .
jQuery.grep(a, f(elt,idx):boolean, [invert=false]):array
, , f
true. , invert true, ,
f false.
jQuery.inArray(v, a):integer
v a , ,
1.
jQuery.isArray(x):boolean
true, x .
jQuery.isEmptyObject(x):boolean
true, x .
jQuery.isFunction(x):boolean
true, x .
jQuery.isPlainObject(x):boolean
true, x , ,
.
jQuery.isXMLDoc(x):true
true, x XML- XML.
jQuery.makeArray(a):array
, , a,
.
jQuery.map(a, f(elt, idx)):array
, , f
a ( , ). null,
f,
.
jQuery.merge(a,b):array
b a a.
, , .
jQuery.noConflict([radical=false])
$ ,
jQuery, jQuery. radical
true, jQuery.
jQuery.proxy(f, o):function
jQuery.proxy(o, name):function
, f o, ,
o[name] o.

984

JavaScript

jQuery.queue(elt, [qname="fx"], [f])


elt
f . , $(elt).queue(qname, f).
jQuery.removeData(elt, [name]):void
elt
.
jQuery.support
, , ,
.
. IE jQuery.support.boxModel false
.
jQuery.trim(s):string
s,
.

KeyEvent
. Event

Label
<label>

Node, Element

Label <label> HTML-.

readonly Element control


FormControl, Label.
htmlFor, ,
htmlFor.
FormControl <label>.
readonly Form form
Form, . , HTML form, Form, id
.
string htmlFor
HTML- for. for JavaScript
,
html, . ,
id FormControl,
. ( FormControl
Label.)

Link
HTML-

Node, Element

HTML- <a>, <area> <link>. <a>


. <area>
, . <link>
<head> ,

Link

985

. <a> <area> JavaScript


. <link>
, .
Link, <a>, ,
href.

, , Link ,
HTML-: hreflang, media, ping, rel, sizes, target type.
, , URL-
( host pathname) href
, <a> <area> <link>,
sheet, disabled relList <link>,
.
boolean disabled
<link>, , ,
.
string hash
href,
(#), : #results.
string host
href, : http://www.oreil
ly.com:1234.
string hostname
href, : http://www.oreilly.com.
string href
href . <a> <area>
, .
string pathname
href, : /catalog/search.
html.
string port
href, : 1234.
string protocol
href,
, : http:.
readonly DOMTokenList relList
classList Element ,
HTML- rel <link>.
string search
href,
, : ?q=JavaScript&m=10.
readonly CSSStyleSheet sheet
<link>, ,
.

986

JavaScript

string text
<a> <area>.
Node.textContent.
string title
HTML- title,
.
<link>, rel alternate stylesheet,
,
, ,
title
.

Location

location Window Document Location,
- () . href
URL- ,
Location URL-.
URL- Link. Location
, href. ,
location.href location.
Location URL-,
. , URL-, Location
href, - URL-
.
URL-. , search,
URL- .
hash, ,
. hash ,
, .

Location URL-
.
() URL-:
http://www.oreilly.com:1234/catalog/search.html?q=JavaScript&m=10#results

string hash
URL-, (#),
#results. URL-
.
string host
URL-, , : http://www.oreilly.
com:1234.
string hostname
URL-, , : http://www.oreilly.com.

MediaElement

987

string href
URL- , Loca
tion, URL-.
URL- ,
URL-. Location
, Location
.
string pathname
URL-, : /catalog/search.html.
string port
URL-, : 1234. ,
, .
string protocol
URL-, , : http:.
string search
URL-, ,
, : ?q=JavaScript&m=10.

void assign(string url)


url, url
href.
void reload()
.
void replace(string url)
url,
, Back
.

MediaElement

Node, Element

MediaElement <audio> <video>.


,
, Audio Video,
- .
21.2, .

NETWORK networkState,
HAVE readyState.
unsigned short NETWORK_EMPTY = 0
.
src.
unsigned short NETWORK_IDLE = 1
. ,

988

JavaScript

. , , preload none,
.
unsigned short NETWORK_LOADING = 2
.
unsigned short NETWORK_NO_SOURCE = 3
,
.
unsigned short HAVE_NOTHING = 0
.
unsigned short HAVE_METADATA = 1
,
. ,
, ,
currentTime,
currentTime.
unsigned short HAVE_CURRENT_DATA = 2
currentTime ,
, .
, , .
- .
unsigned short HAVE_FUTURE_DATA = 3
, , , ,
, ,
.
unsigned short HAVE_ENOUGH_DATA = 4
, ,
.

boolean autoplay
true, ,
. HTML-
autoplay.
readonly TimeRanges buffered
.
boolean controls
true,
. HTML- controls.
readonly string currentSrc
URL- , src
<source>, ,
.
double currentTime
.
.

MediaElement

989

double defaultPlaybackRate
, .
1.0.
readonly double duration
. (
, ),
NaN.
, Infinity.
readonly boolean ended
true, .
readonly MediaError error
, ,
null. , code .
readonly double initialTime
. 0,
(, )
.
boolean loop
true,
. HTML loop.
boolean muted
, .
, . <video>
audio="muted", .
readonly unsigned short networkState
, .
.
readonly boolean paused
true, .
double playbackRate
. 1.0 .
1.0 .
0 1.0 .
0 . (
,
.)
readonly TimeRanges played
, .
string preload
HTML- ,
, , ,
. none ,
. metadata
, (
), . auto (

990

JavaScript

, preload ) ,
, .
readonly unsigned short readyState
, ,
. HAVE_,
.
readonly TimeRanges seekable
,
currentTime.
0 duration.
,
.
readonly boolean seeking
true,
currentTime.
, true
.
, seeking true
.
string src
HTML- src .

. currentSrc.
readonly Date startOffsetTime
0,
. ( , .)
double volume
.
0 1. . muted.


<audio> <video> ,
HTML- JavaScript-.
,
addEventListener()
(EventTarget). ,
, .
Event.

, ...

onabort

, ,
. error.code error.MEDIA_ERR_ABORTED.

oncanplay

, ,
.

oncanplaythrough ,
.
ondurationchange duration.

991

MediaElement

, ...

onemptied

networkState NETWORK_EMPTY
.

onended

onerror

- .
error.code , MEDIA_ERR_ABORTED (Media
Error).

onloadeddata

onloadedmetadata ,
.
onloadstart

onpause

pause(), .

onplay

play(), autoplay
.

onplaying

onprogress

. 2 8
. , ,
, Event, ProgressEvent,
,
progress.

onratechange

playbackRate defaultPlaybackRate.

onseeked

seeking false.

onseeking


, ,
.
seeking true.

onstalled

, .

onsuspend

ontimeupdate

currentTime.
4 60 .

onvolumechange

volume muted.

onwaiting

,
- .
, playing.

string canPlayType(string type)


,
MIME- type. ,
, .
( ), ,
probably ().
probably, type codecs=

992

JavaScript

. ,
, maybe.
void load()

. ,
, ,
src. ,
<source> load() .
void pause()
.
void play()
.

MediaError
<audio> <video>
<audio> <video> , error
error MediaError.
code .
.

unsigned short MEDIA_ERR_ABORTED = 1


.
unsigned short MEDIA_ERR_NETWORK = 2
,
.
unsigned short MEDIA_ERR_DECODE = 3
,
.
unsigned short MEDIA_ERR_SRC_NOT_SUPPORTED = 4
, src,
.

readonly unsigned short code


.
, .

MessageChannel
MessagePorts
MessageChannel Messa
gePort. postMessage() message
. Window
Worker, MessageChannel
MessagePort (
ports postMessage()).

MessageEvent

993

MessageChannel MessagePort ,
HTML5,
(22.3) (
22.4) MessagePort.

new MessageChannel()
, , Message
Channel.

readonly MessagePort port1


readonly MessagePort port2
, .
:
, Window
Worker, .

MessageEvent

Event

message
.
Window, Worker, WebSocket, EventSource MessagePort
onmessage message. ,
message, , JavaScript,
,
22. MessageEvent
data. , message,
MessageEvent. message
, ,
.

readonly any data


. data
,
( 22).
JavaScript, ,
. JavaScript, Document
Element, , Blob ArrayBuffer.
readonly string lastEventId
message EventSource (18.3)
lastEventId, , .
readonly string origin
message EventSource (18.3) Window (
22.3) URL- .

994

JavaScript

readonly MessagePort[] ports


message Window ( 22.3), Worker ( 22.4)
MessagePort MessagePort,
postMessage().
readonly Window source
message Window (22.3)
Window, .

MessagePort

EventTarget

MessagePort
, ,
. MessagePort
: . MessageChannel. postMessage() MessagePort
message MessagePort.
( 22.3)
(22.4) postMessage()
message.
MessagePort. MessageChannel MessagePort
, ,
,
.
MessageChannel MessagePort ,
HTML5,
(22.3) (
22.4) MessagePort.

void close()
MessagePort , (
). postMessage()
, message .
void postMessage(any message, [MessagePort[] ports])
message
message , e . ports,
message. message
,
( 22).
void start()
message MessagePort.
, ,
.
, . ,
, ,
addEventListener() EventTarget.
onmessage, start() .

Meter

995


onmessage
message. message
MessagePort. ,
. ,
start(),
message.

Meter
,

Node, Element

Meter HTML- <meter>,


,
,
.
HTML-
. , HTML .
<meter> HTML5,
.

readonly Form form


Form, ,
HTML- form.
double high
, high max
.
readonly NodeList labels
, , Label,
.
double low
, low max
.
double max
, <meter>.
1.
double min
, <meter>.
0.
double optimum
, .
double value
, <meter>.

996

JavaScript

MouseEvent
. Event

Navigator
-
Navigator , -.

. , , Netscape Navigator,
.
Navigator, navigator
Window.
Navigator ,
,
. 14.3 ,
14.4 ,
Navigator. ,
, 13.4.3.

readonly string appName


. , Netscape,
Netscape. Internet Explorer Microsoft Internet Explorer.

, , .
readonly string appVersion
.

.
readonly Geolocation geolocation
Geolocation .

.
readonly boolean onLine
false, . ,
, , ,
. -
( ), true.
, online
offline Window.
readonly string platform
/ ,
. ,
: Win32, MacPPC Linux i586.
readonly string userAgent
, user-agent HTTP-.
:

997

Node
Mozilla/5.0 (X11; U; Linux i686; en-US)
AppleWebKit/534.16 (KHTML, like Gecko)
Chrome/10.0.648.45
Safari/534.16

void registerContentHandler(string mimeType, string url, string title)


url ,
mimeType. title ,
. url
%s.
- mimeType, URL- -
url %s.
URL-. , HTML5,
.
void registerProtocolHandler(string scheme, string url, string title)
registerContentHandler(), -
scheme, URL. scheme , mailto sms
. , HTML5,
.
void yieldForStorageUpdates()
, Document.cookie, Window.localStorage Window.ses
sionStorage (. Storage 20), ,

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

Node
( Document)
Node,
. parentNode childNodes[]
.
, childNodes[] firstChild
nextSibling ( lastChild previousSibling ).
appendChild(), insertBefore(), removeChild() replaceChild()
, .
Node,
, , Element Text. nodeType ,
.
,
. :
var n; // ,
if (n.nodeType == 1) { // Node.ELEMENT_NODE

998

JavaScript

var tagname = n.tagName; // Element,


}

unsigned short ELEMENT_NODE = 1


unsigned short TEXT_NODE = 3
unsigned short PROCESSING_INSTRUCTION_NODE = 7
unsigned short COMMENT_NODE = 8
unsigned short DOCUMENT_NODE = 9
unsigned short DOCUMENT_TYPE_NODE = 10
unsigned short DOCUMENT_FRAGMENT_NODE = 11
nodeType.
, - Node()
Node. ,
IE 8 .
.
unsigned short DOCUMENT_POSITION_DISCONNECTED = 0x01
unsigned short DOCUMENT_POSITION_PRECEDING = 0x02
unsigned short DOCUMENT_POSITION_FOLLOWING = 0x04
unsigned short DOCUMENT_POSITION_CONTAINS = 0x08
unsigned short DOCUMENT_POSITION_CONTAINED_BY = 0x10
,
, compareDocumentPosition().

readonly string baseURI


URL- Node,
URL-. HTML URL- <base> Docu
ment.URL, .
readonly NodeList childNodes
, ,
. null: ,
, childNodes length, .
: NodeList , ..
NodeList.
readonly Node firstChild
null, .
readonly Node lastChild
null, .
readonly Node nextSibling
, child
Nodes[] parentNode, null, .
readonly string nodeName
. Element ,
tagName Element.
,
.

Node

999

readonly unsigned short nodeType


, .. , .
. ..
Internet Explorer,
. HTML-
: 1 Element, 3 Text, 8 Comment
9 Document .
string nodeValue
. Text .
readonly Document ownerDocument
Document, . Document
null. , ,
.
readonly Node parentNode
( -) null,
. : Document DocumentFragment
. , , ,
,
parentNode null.
readonly Node previousSibling
, child
Nodes[] parentNode, null, .
string textContent
Text Comment data.
Element DocumentFragment
Text. Element
DocumentFragment
Text .

Node appendChild(Node newChild)


newChild ,
. newChild ,
. newChild
DocumentFragment, , childNo
des[] Document
Fragment. , (
) .
ownerDocument newChild ownerDocument
. (. Document.adoptNode()). .
Node cloneNode(boolean deep)
, .
true, .
, .
, parentNode
null. Element, .
, - ,
, .

1000

JavaScript

unsigned short compareDocumentPosition(Node other)


other
, .
, , ..
0.
. DOCUMENT_POSITION_, ,
:
DOCUMENT_POSITION_
DISCONNECTED

0x01

,
.

PRECEDING

0x02

other .

FOLLOWING

0x04

other .

CONTAINS

0x08

other .
, PRECEDING.

CONTAINED_BY

0x10

other .
,
FOLLOWING.

boolean hasChildNodes()
true, ,
false .
Node insertBefore(Node newChild, Node refChild)
newChild
. childNodes[]
, refChild.
refChild null, newChild
childNodes[], appendChild(). ,
refChild ,
.
newChild ,
. newChild Docu
mentFragment, ,
, .
boolean isDefaultNamespace(string namespace)
true, URL- namespace URL , lookupName
spaceURI(null), false .
boolean isEqualNode(Node other)
true, other , ..
, , () .
false, .
boolean isSameNode(Node other)
true, other ,
false .
==.

NodeList

1001

string lookupNamespaceURI(string prefix)


URL- ,
prefix, null, .
prefix null, URL-
.
string lookupPrefix(string namespace)
, URL-
, null, .
void normalize()
, ,
.
,
.
Node removeChild(Node oldChild)
oldChild childNodes[] .
, , .
removeChild() oldChild . old
Child
.
Node replaceChild(Node newChild, Node oldChild)
oldChild newChild. oldChild
. newChild
,
. newChild DocumentFragment,
newChild , oldChild,
.

NodeList
, ,
NodeList , ,
Node ( ). length ,
; , 0 length-1.
NodeList
item(). NodeList Node: Node
List (null) .
NodeList, , childNodes
Document.getElementsByTagName(), Element.getElementsByTagName() HTMLDocu
ment.getElementsByName(). NodeList ,
, ,
childNodes[].
: NodeList :
. , NodeList
,
NodeList.
NodeList, (,
), NodeList!

1002

JavaScript

readonly unsigned long length


NodeList.

Node item(unsigned long index)


index null, index .

Option
<option> Select

Node, Element

Option Select.
, ,
, , options[]
Select, ,
.
Option ,
Option. (,
Document.createElement().)
Option options Select.
HTMLOptionsCollection.

new Option([string text, string value, boolean defaultSelected, boolean selected])


Option() <option>.
textContent (. Node)
value, defaultSelected selected.

boolean defaultSelected
HTML- selected.
, ,
.
boolean disabled
true , <option> .
, <optgroup>
HTML- disabled.
readonly Form form
<form>, , Option.
readonly long index
Option Select. (.
HTMLOptionsCollection.)
string label
HTML- label, , text
Content (. Node) Option.
boolean selected
true, ,
false .

Output

1003

string text
textContent (. Node) Option,
,
.
string value
HTML- value, , text
Content.

Output
<output> HTML-

Node, Element, FormControl

Output <output> HTML-. ,


, Output FormControl.

string defaultValue
textContent (. Node)
Output. , value
. Output
defaultValue,
defaultValue. .
readonly DOMSettableTokenList htmlFor
HTML- for <output> id ,
, ,
<output>. for JavaScript
, htmlFor.
, ,
DOMTokenList .

PageTransitionEvent
pageshow pagehide Event
, load
pageshow pageshow ,
. pageshow
PageTransitionEvent, persisted true,
, .
PageTransitionEvent pagehide,
pagehide persisted
true.
pageshow pagehide Window.
, .

readonly boolean persisted


pageshow false,
( ) .
true, .
pagehide true.

1004

JavaScript

PopStateEvent

Event

-, ( 22.2),
pushState() History
,
. Back Forward,
, popstate
Window
PopStateEvent.

readonly any state


,
, History.pushState() History.replaceState().
,
(
22).

ProcessingInstruction
XML-

Node

XML-
. , HTML-,
ProcessingInstruction.

string data
(..
?>, ).
readonly string target
. ,
<?; ,
.

Progress

Node, Element

Progress HTML- <progress>


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

.
<progress> HTML5,
.

ProgressEvent

1005

readonly Form form


Form, ,
HTML- form.
readonly NodeList labels
, , Label,
.
double max
, . ,
Progress ,
XMLHttpRequest,
, . HTML max. 1.0.
readonly double position
Progress ,
value/max. 1.
double value
0 max, .
HTML- value. ,
Progress . , Prog
ress .
(, MediaEle
ment stalled), removeAttribute()
Element.

ProgressEvent
,

Event

ApplicationCache, FileReader XMLHttpRequest ( 2)


, ,
/ .
, progress.
, FileReader XMLHttp
Request, loadstart, load, loadend, error abort.
XMLHttpRequest timeout. ApplicationCache
,
, progress.
, loadstart
loadend. loadend
load, error abort,
. loadstart
( progress). ( ApplicationCache
, progress
,
.)
ProgressEvent,
. ProgressEvent
HTML- <progress>, Progress,

1006

JavaScript

ProgressEvent, () onprogress XMLHttp


Request, <progress>,
.

readonly boolean lengthComputable


true, ,
, false . true,
e ProgressEvent :
var percentComplete = Math.floor(100*e.loaded/e.total);

readonly unsigned long loaded


.
readonly unsigned long total
, , , 0
. , ,
size Blob Content-Length,

Вам также может понравиться