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

1

1
oREILLY

JavaScript
JavaScript. " 'l'
JavaScript - ECMAScript 6.0 (S) - 'l''l'
'l'
, - . JS.
( ) S
'l'
. 'l'

, Web Development with Node and Express,


. 'l' -

(,
'l' 'l'O
, ), ,
, 'l'
.
!"
, -
Node.js. (/ Simpson),
Don't Know JS

S
ES5 "
'l'
,
JavaScript,
JavaScript
ECAScript ".
JavaScript
w
-
(/ Rauschmayer),
Speaking JavaScript
,
, -


,
Node.js

-
Egieerig at Art,
- - ,
.
20- .

/ JAVASCRIPT ISBN 978-5-9908463-9-5

DJ JU.1Emu.i
www.dialektika.com

Twitter: @oreillymedia
facebook.com/oreilly 9 785990 846395

JavaScript
Learning
JavaScript

THIRD EDIION

Ethan Brown

Beijing Cambridge Farnham Kln Sebastopol Tokyo



O"REILLY

JavaScript

3-

-
2017
32.973.26-018.2.75
87
681 .3.07
""
. ..
..
"" :
info@dialektika.com, http://www.dialektika.com
, .
87 JavaScript: -, 3- . :
. . - . : "-'; 2017. - 368 . : . - . .
ISBN 978-5-9908463-9-5 (.)

32.973.26-018.2.75

.


, ,
,
O'Reilly & Associates.
Authorized Rssia translation of the English edition of Learning favaScript (ISBN 978-1-491-91491-5)
2016 Ethan Brown.

This translatio is pulished d sold permissio of O'Reilly Media, !., which ows or cotrols all rights
to publish d sell the same.

All rights reserved. No part of this work reprodced or trasmitted i any form or meas,
electroic or mechaical, icludig photocopyig, recordig, or any information storage or retrieval system,
without the prior written permission of the copyright owner and the Pulisher.

-

JavaScript
-
3-

..
..
..
..

23.03.2017. 70100/16.
Times.
. . . 23,0. .-. . 17,8.
500 . 2261



142300, 11, . , . , . 1

"- 195027, -, " . 30

ISBN 978-5-9908463-9-5 (.) 2017, "11':


, 11,
ISBN 978-1-491-91491-5 (.) 2016, Ethan Brown
r

17
1. 25
2. JavaScript 39
3. , , 57
4. 81
5. 105
6. 129
7. 145
8. 159
9. - 175
1. 191
11. 197
12. 205
13. 215
14. 231
15. 253
16. Math 263
17. 271
18. JavaScript 293
19. jQuery 313
20. Node 319
21. - 339
22. 351
. 357
. 361
363

16
16

17
JavaScript 18
ES6 19
20
20
, 20
21
24

1. 25
26
26
28
29
JavaScript 31
jQuery 32
33
35
36
Hello, World 37

2. JavaScript 39
ES6 39
ES6 41
Git 41
41
42
Git: 43
: npm 46
: Gulp Grunt 48
49
50
Babel Gulp 50
52
55

3. , , 57
57
: ? 58
59
60
61
62
64
64
65
66
67
68
69
69
nul l undefined 69
70
Number, String Boolean 72
73
' 75
75
76
76
77
77
78
78
79

4. 81
81
whi le 84
85
86

7
87
if."else 87
do. . . while 89
for 90
if 91
92
JavaScript 93
94
if. . .else 94
95
for 96
switch 97
for.. . in 101
for...of 101
1 02
continue 102
break return 102
103
103
104

5. 105
107
107
1 10
111
1 13
1 14
1 15
115
AND, OR NOT 1 16
1 17
1 18
118
"" 1 19
1 19
1 19
typeof 121
void 1 22
1 22
1 24
125

8
126
126
if ...else 126
if 127
127

6. 129
130
130
131
133
134
135
135
this 136
138
140
cal l, apply ind 141
143

7. 145
146
146
147
149
150
, 151
153
154
1 56
157
157
158

8. 159
159
160
161
161
162
162

9
162
163
163
164
: map fil ter 166
: reduce 168
171
172
173

9. - 175
175
for...in 176
Obj ect.keys 176
- 177
178
179
181
181
183
184
185
() 186
187
, 188
190

1. 191
191
193
194
195
196

11. 197
Error 197
try catch 198
199
200
try...catch . ..finally 202
203

10
12. 205
207
209
yield 210
return 212
213

13. 215
215
, 216
. . . 217
? 220
221
22 1
223
225
227
228
229
230

14. 231
232
232
setinterva l clearinterval 234
234
236
237
238
239
240
241
244
245
246
? 249
250
250
251

15. 253
, , Unix 253
Da te 254

11
Moment.j s 255
JavaScript 256
256
256
257
257
258
260
260
261
261
262

16. Math 263


263
264
264
264
265
- 265
266
266
266
267
267
268
269
269

17. 271
271
272
273
273
274
276
HTML- 277
278
279
280
"" 281

12
, 282
282
283
284
285
286
289
289
290
292
292

18. JavaScript 293


ESS S? 293
294
297
- DOM 297
DOM 298
DOM 299
DOM 299
300
301
302
303
307
Ajax 308
312

1 9. jQuery 313
() 313
jQuery 314
DOM 314
DOM jQuery 314
315
jQuery 317
Ajax 318
318

20. Node 319


Node 319
320

13
, nm- 322
- 325
327
proces s 330
333
333
335
- 336
338

21. - 339
: 339
341
: , 343
- 346
349

22. 35 1
35 1
352
352
Stack Overflow 353
Open Source 356
356
. 357

. 361
363

14
- .

- Engineering at
Art, , - -
, .
20- ,
JavaScript - .


- (Diceros blcornis).
- .
, - .
. ,
, -, .
.
:
.
.
, .
- , ..
. .
,
, . , ,
.
.
.
14-18 ,
,
. ,
.
.

, 2400.
, , .
.
O'Reilly ;
. , ,
anima l s . ore i l l y . . Natural History
(John Cassell).
JavaScript, JavaScript
. ,
JavaScript 2012 .
, .
: JavaScript ""
( , , ), , ,
-.
. ES6 ,
, (Brendan Eich), , ,
, ,
, (
, ).
, JavaScript .
, -
JavaScript, , .
, (
) .
, JavaScript , , (
)
, . , ,
JavaScript. , ,
: - , - ,
.
, , ,
, . ,
(, , ).
, . , ,
, . (,
) . .
. "?"
"" JavaScript,
.
, .
.
JavaScript .
( ), -, , -
, 5-1 . , HTML5 ES6,
-
. Node.js JavaScript ;
,
, , -
. , ,
1980- .

JavaScript
JavaScript Netscape
Communications Corporation 1 995 .
, JavaScript
. :
, JavaScript
. , , 1 5 ,
.
"JavaScript", Netscape Navigator
1 995 "Mocha", "LiveScript". "Java"
"JavaScript" , :
, JavaScript Self (
, Xerox PARC 1 980- ) Scheme
(, 1 970- (Guy Steele)
(Gerald Sussman) Lisp ALGOL), Java.
Self, Scheme
"JavaScript': "JavaScript"
Java, 1
1996 Netscape JavaScript
Ecma -
, .
Ecma International -26,
JavaScript.
Ecma ( ECMAScript)
JavaScript . JavaScript -

1 20 1 4 .

18
ECMAScript, "JavaScript" "ECMAScript"
.
ECMAScript, 5.1 ( "ES5"),
201 1 . , ECMAScript 5.1,
, , ECMAScript 5. 1
.
ECMAScript 6 (S), ,
Ecma International 2015 .
"Harmony" (),
S, "Harmony'; "S Harmony'; "S'; "ES201 5" "ECMAScript 201 5".
"S".

S
"
ES5, S?"
S
JavaScript, ES5
S. , S
( ES5 ). (
), S
, " " ES5.
S
,
( ,
( ) , ).
, , S - JavaScript,
, , ,
, .
S.
, ES5,
S.
, .
1 , S, ES5.
, S ES5,
, " ES5" ,
" S': ,
ES5,
( , - !).

19
S .
S ,
. , , ESS, S,
.


, , ,
(
) .
, .
, JavaScript (
ESS),
. , JavaScript ,
.
-
, , ,
JavaScript.
(, , ),
( , ).
,
, : , ,
.


- JavaScript
. Mozilla Developer Network (MDN) ,
, ]avaScript,
. ,
(David Flanagan) ]avaScript.
( S ).

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

20
, ,
.
.
,
, :
BINDSIZE= ( )* ( ).
:
( ).
Menu Option

. ,
,
.

& .

O'Reilly ,
. (Simon St. Laurent) ,
. (Meg Foley), , ,
. O'Reilly -
-

, (Rachel Monaghan) ,
(Kristen Brown) (Jasmine
Kwityn) , . !
(Matt Inman),
(Shelley Powers), (Nick Pinkham) (Cody Lindley)
, .
, , , .
, :
,
(Stephen Colbert) !

21
( )
, , ,
(
!).

(Web Development with Node and Express). (
!), , ,
. , ,
: !
Engineering at Art,
. - . ,
, - ,
. (Tom Paul)
: ,
.
(Steve Rosenbaum) , Art,
. ,
(Colwyn Fritze-Moor) (Eric Buchmann)
, , . !
(Dylan Hallstrom) , .
(Liz ) (Sam Wilskey) ,
Art! (Carole Hardy),
(Nikki Brovold), (Jennife Erts), (Randy Keener),
(Patick Wu) (Lisa Melogue) .
, , : (
Alferez), (Paul Inman) (Dl Olds).
(
) (Dan Resler), -
.
,
. , (
).
PSU . -
! - , , , , .,
, ., , , ., . :
!
Art, .
(Mark Booth): ;
. .
. (Katy Roberts) ,

22
, . , .
(Sarah Lewis): . (Byron)
(Amber C1ayton) - ,
. (Lorraine), , 2.
(Kate Nahas): ;
. : ,
. ( Chris
Onstad) (Jessica Rowe):
, , .
, : , .
, , ,
. (, ,
). , , ,
.

2 . - . .

23

, , .
, ,
.
, .
.
-, .
, , ,
,
.
, ,
e-mail.
. :
E-mail: info@dialekt ika . com
WWW: http : / /www . dialekt i ka . com
:
: 195027, -, ., . 30, 1 16
: 03 1 50, , / 1 52

24
1

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

,
,
.
, .
,
, , ,
. JavaScript, ,
. ,
, .
, , :
, , ,
, ,
.
, , " -':
. -
, .

"Hello, World"
(, ), ''hello world".
, 1 972 ,
, Bell Labs. The
Programming Language1,
1 , . . , 2- , ISBN 978-5-8459-
1 975-5, . " "': 201 7.
1 978 .
, ,
.
"Hello, World"
,
, 1978 : ,
-, . , -
, ; ,
; , 2.
, , . ,
( , )
, , , ", ':
,
44 , , .
'ello world" , ,
, 1972 .

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


, ,
. ,
: .

2 , , ,
.

26 1.
,
, . Internet Explorer,
, Chrome,
Firefox, Safari Opera. , - Firefox,
, .
, , Firefox.
, Firefox.
, .
( ). ,

. - vi/vim Emacs.
, ,
, SSH, ..

.
( ) .
, , ,

. - Atom, Sulime Text, Coda,
Visual Studio, Notepad++, TextPad Xcode.
, , , .
Windows,
(Notepad++ - Windows).
,
, .


,
. ,
, - ( , !).
.
;
, ,
.


,
.
; ,
. ,
, .. ""; ,

27
. ,
,
.
-, .
- ,
, .


( code folding)
. ,
. ,
. ,
- .

( (word completion), IntelliSense3)


-
, , , ,
. . - .
, , encodeURIComponent, enc,
encodeURIComponent . - . ,
enc, encodeURIComponent, ,
encodeURI.
, .
JavaScript , ,
, - (
). , , ,
, .
, (vim, )
, .


JavaScript, ,
(comment) .
JavaScript; .
, .
, .
JavaScript : .
( / / ) .

3 Microsoft.

28 1.
( / * ) ,
( * /). .
.
console . log ( 11echo11 ) ; 11 "ech o "
/*
, , - : Java Script ,
.
, Ja va Script .
Ja va Script .
,
.
*/
/* , , ! */
(Cascading Style Sheet - CSS),
, JavaScript
( CSS ). HTML ( CSS)
, JavaScript.
< ! >. - -

<head>
<title>HTML and CSS Example</title>
<! HTML . . .
--

: . -->
<style>
body : { color : red; }
/ * CSS . . .
: . * /
</style>
<script>
console . log ( 11echo11 ) ; 11 JavaScript . . .
/* . . ,
.

. * /
< / s cript>
< /head>


: HTML, CSS
JavaScript. HTML ( JavaScript
CSS HTML),
. ,
:
, .

29
,
- , . ,
, ,
.
,
, , .
. ,
ESS, ES6 (Harmony).
, ,
, S. ,
S "" ,
.
S. ,
ESS .

, ,
. ,
.

JavaScript. , main . j s.
.
console . log ( ' main . j s loaded ' ) ;

CSS, main . css. ,


, ,
.
/ * . * /

index . html.
< ! doctype html>
<html>
<head>
<link rel=" s tylesheet " href= "ma in . cs s " >
< /head>
<body>
<hl>My first app l i cat ion ! </hl>
<p>Welcome t o < i >Learning Java S cript , rd Edit ion< / i > . < /p>

< s cript s rc="main . j s " >< / s cript>


< /body>
< /html>

HTML -,
JavaScript ,

30 1.
HTML, JavaScript.
HTML : (head) (body).
,
( , ).
, .
, ,
( ,
<script>, , CSS ).
< l ink rel=" styleshee t " href= "ma i n . css " >;
CSS .
, , <script s rc="main. j s " >< / script>,
JavaScript . ,
, . <script> , ,
, ,
, .
<hl>My first application ! </hl>,
(
), <> (),
, ( < i > ).
index . html .
, (
). HTML.

. HTML
JavaScript ,
: ,
.
,
.

JavaScript
JavaScript: cons o l e . log ( ' main . j s l oaded ' ) .
? (console) - ,
.
.
.
,
. Firefox - <Ctrl+Shift+K> ( Windows Linux)
<Command+Option+K> ( ).
, index . html, JavaScript;
"main.js loaded" (main.js ) ( ,
). cons ol e . log - 4 ,
.
,
, ]avaScript,
- , JavaScript
.

jQuery

- jQery. ,
,
. ,
jQuery, .
jQuery
mai n . j s:
< script src="http s : / /code . j query . com/j query- 2 . 1 . 1 . min . j s " >< / s cript>

< s cript src="main . j s " >< / s cript>

, URL , ,
.
jQuery (Content Delivery
Network - CDN),
. ,
.
ma in . j s , jQuery:
$ ( document ) . ready ( funct ion ( ) {
' us e s t ri c t ' ;
console . log ( ' main . j s loaded ' ) ;
});

jQuery, , , -
. , .
jQuery ,
HTML, JavaScript (
consol e . log). , JavaScript
, : JavaScript,

4 9.

32 1.
, $ ( docwnent ) . ready ( function ( ) { ) ) ; .
, ' us e s trict ' ,
-

, JavaScript
.
, JavaScript
. , ,
JavaScript!

r
HTMLS
. (canvas) HTMLS
, , .
,
Pape r . j s, HTMLS.

Pape r . j s
- .
, KineticJS,
Fabric . j s EaselJS. ,
.

Pape r . j s,
HTML . (
, ):
<canvas id="mainCanva s " ></canvas>

, id:
JavaScript CSS.
, ;
, , , .
.

-1 HTML .

(),
. "mainCanvas",
.
.
,

.

33
main . c s s , .
CSS, . CSS
HTML, .5
#mainCanvas {
width : 4 0 0 ;
height : 4 0 0 ;
border : solid lpx k ;

, .
, Pape r . j s,
. jQuery,
main . j s, .
< s cript src="https : / / cdnj s . cloudflare . com/ a j a x / l ib s /paper . j s / 0 . 9 . 2 4 / l
paper-full . min . j s " >< / s cript>

: Paper . j s
CDN, jQuery.

, .
jQuery Paper . j s
mai n . j s, .
, , -
,
jQuery ( ), -
.

, Pape r . j s,
. (
) (boilerplate).
main . j s, ' use strict ' ( , console . log):
paper . install ( window) ;
paper . se tup ( document . getElementByid ( ' mainCanvas ' ) ) ;

/ / TODO

paper . view . draw ( ) ;

Pape r . j s
( 7).
Paper . j s . ,

5 , CSS HTML, HTML CSS

Codecaderny.

34 1.
TODO, .
Pape r . j s .
, , - !
. "TODO"
.
var = Shape . Circle ( 2 0 0 , 2 0 0 , 5 0 ) ;
c . fil lColor = ' green ' ;

.
JavaScript.
, .
(object) (argument):
, . , 400
400 , -
(200, 200). 50
. ,
( (stroke), Paper . j s).
.


, , ,
. ,
64 . ,
63 ,
. , ?
, .
, 64 .
, , .
var ;
for ( var =2 5 ; <4 0 0 ; +=5 0 ) {
for ( var =2 5 ; <4 0 0 ; +=5 0 )
= Shape . Circle ( x , , 2 0 ) ;
c . f i l lColor = ' green ' ;

, 64 !
, ,
, 1 28 .
, , for.
, 4. for

35
(25), (, 400)
(50).
.

.
:
,
.
: ,
(64), , ,
.
,
64
.


, , .
, .
. ,
, .
.
(asynchronous event) - ,
. -
: , . ,
, (
) - . ,
, ,
.
Paper . j s
"tool" ().
, : ,
Pape r . j s .6 ,
"tool" () "user input tool" (
). , , :
var t ool = new Tool ( ) ;

tool . onMouseDown = funct ion ( event )


var = Shape . Circle ( event . point . x , event . po int . y, 2 0 ) ;

6 , Pape r . j s , ,
Photoshop, "hand tool'', "direct selection tool" ..

36 1.
c . f il lColor ' green ' ;
};

. ,
(event handler), -
onMous eDown. ,
, , 1 .
. : ,
. ,
, - .
, function,
, .
: , -
, , .
, event . point, , ,
.
: ,
Circle ( ).
var = Shape . Circle ( event . point , 2 0 ) ;

JavaScript:
. ,
, , , .
, , - point, - .
6 9.

Hello, World
1 972 .
, .
onMouseDown .
var = Shape . Circle ( 2 0 0 , 2 0 0 , 8 0 ) ;
c . fi l lColor = ' k ' ;
var text = new PointTex t ( 2 0 0 , 2 0 0 ) ;
text . j us t i fication = ' center ' ;
text . f i l lColor = ' wh i t e ' ;
text . font S i z e = 2 0 ;
text . content = ' he l l o world ' ;

: ,
, ( PointText ) .
( )

Hel lo, World 37


(, ).
('ello world" ( )).
, ,
JavaScript: cons ol e . log . ,
"hello world': , ,
1972 , -
: , , .
,
"Hello, World". "Hello, World':
: ! , ,
JavaScript.

38 1.
2

JavaScript

JavaScript
( ), JavaScript
. ,
S,
S ESS.
, , ,

. .
Git - ,
.
Node JavaScript (
npm,
).
Gulp- (build tool),
( - Grunt).
Babel - (transcompiler), S
ESS.
ESLint - (linter),
!

(JavaScript).

, JavaScript.

S r
. -
S ( Harmony, JavaScript 201 5) ,
JavaScript. -
. , ,
, S
"" ESS .
" ! -
, , !"
, ,
: ,
JavaScript.1
JavaScript :
, Node
. ,
, , ,
S, . - Node,
: JavaScript,
S Node.

S Firefox
-, S Fiddle.
, .

JavaScript ESS S -
, . , ,
, , ( )
, S.
JavaScript,
. , ,
(evergreen):
, . , ,
,
( , ).
, ,
,
.
,
S
. (transpilation) -

1 JavaScript (, Node) JavaScript,

40 2. JavaScript
S
ES6 ,
, , .
, kangax -
ES6 ( ES7). 201 5
(Babel) 72%. ,
Babel ,
, , .
,
.
( ,
). ,
, .

Git
Git , (
) Git.

(terminal),
(command line) (command shell)).
- ,
. , ,
, , :
, ,
,
.
( ) bash;
Linux, OS . Windows
, Git (
) bash,
. bash.
, (prompt);
.
, , ($).
, ,
. , . ,
, l s .

S 41
$ ls

Unix, , bash,
(/). Windows,
( \), Git
. (
) bash ( ) .

( cd)
(mkdir). , ,
$ cd

pwd (print working directory - ) ,


.
$ pwd

test,
$ mkdir test

,
$ cd test

( . . ) - .
"" ( ,
),
$ cd "

, - ,
. ,
Li. , 2-
(. ., "" 201 6, ISBN 978-5-8459-2101 -7).


.
(project root) . ,
, l j ,
.
, .
, , , , -
. , ,
. ,
- /home / j oe/work/l j ,

42 2. J avaScript
puic / j s /tes t . j s, /home / j oe /work/
l j /pu i c/ j s /test . j s.

Git:
,
, . Git,
.
.
$ git init

(
. gi t).
,
: , ..
, . gi t ignore.
. gi tignore .
# npm
npm-debug . log*

#
node modules

# OSX
. DS Store

#
* . tmp
*-

"" , ,
(, , . bak,
* . bak).
git status, . ,
. ,
.
$ git status
On branch ma ster

I n i t i a l commit

Unt racked file s :


( u s e " g i t add < f i l e > . . . " to include in what w i l l committed)

S 43
. gi t i gnore

nothing added t o commit but untra c ke d f iles present ( us e " gi t add" t o track)

Git ,
( . gi tignore ) , unt racked, .. Git .
Git (commit).
-


( ,
Git ). Git ,
, . gitignore .
$ git add . gitignore

;
. gitignore , .
gi t status , .
$ git s tatus
On branch mas t e r

I n i t i a l commit

Changes to commi t t e d :
( use " g i t rm - -cached <file> . . . " to unstage )

new fi l e : . gi tignore

git i gnore (committed).


.

, ,
. gitignore. ,
.
$ git commit -m " Initial commit : added . gitignore . "

, -m, ,
, .

.

. (
. gitignore ) , .
gi t status , .
On branch master
nothing t o commi t , working directory clean

.
. gi tignore npm-debug . log, , ,

44 2. J avaScript
. log (
). . gitignore * . log.
README . md,
, Markdown:
= Learning Java S cript , rd Edit ion
Chapter 2 : Java S cript Devel opment Tools

I n this chapter we ' re learning about Git and other


development tool s .

gi t status.

$ git status
On branch ma ster
Changes not s taged for commit :
( use "git add < f i l e > . . . " t o update what wil l commit t e d )
( u s e "git checkout -- < f i l e> . . . " t o dis card changes i n working directory)

modi fied : . gi tignore

Unt ra cked file s :


( use " g i t add < f i l e > . . . " to include in what w i l l committed)

README . md

: - ( . gi tignore )
- (README . md). ,
.
$ git add . gitignore
$ git add READE . md

, ,
.
$ git add -
$ git commit -m " Ignored all . log files and added READE . md . "

, (
).
, -
, .
, : ,
.
$ git add -
$ git commit -m "<rief description of the changes you just made>"

S 45
gi t add ;
, .
,
, . ,
, ( -
).
Git; Git,
Git Ttorial GitHub Version Control with Git, Second
Edition (Jon Loeliger) (Matthew McCullough).

n : npm
JavaScript npm ,
.
Node. Node
, , npm . ,
npm .
npm Node, , Node,
Node.js
I N STALL (). Node, , npm Node
. .
$ node -v
v4 . 2 . 2
$ npm -v
2.14.7

Node npm . npm


. ,
, ,
.
npm : .
- ,
.
. npm install.
Undersco re, , .
.
$ npm install underscore
underscore@ l . 8 . 3 node modules \underscore

npm , Underscore (
1 .8.3; , , ). Underscore -
-

, npm ;

46 2. J avaScript
!
Underscore, .
$ npm install underscore@ l . 8 . 0
underscore@ l . 8 . 0 node modul e s \ underscore

?
, , node modules;
_

. node modules; _

.
, ; ,
( ), (dependencies)
.
, , npm
package . j son. ,
npm ini t (
<Enter>
;
).
package . j son.

(dev dependencies). - ,
,
( ) . ,
, --save -- saveDev;
, package . j son.
Underscore --save.
$ npm install --save underscore
npm WARN package . j s on l j @ l . 0 . 0 No de scription
npm WARN package . j s on l j @ l . 0 . 0 No repo s i t ory field .
under s core@ l . 8 . 3 node modules \underscore

" ?" npm


.
: ,
npm , .
package . j son , , Underscore
. ,
, package . j son, ,
-

( ) . .
node_modules, npm install ( ,
). npm ,

S 47
package . j son. node_modules,
.

: Gulp Grunt
, ,
(build tool), ,
.
JavaScript Grnt Glp. . Grunt
, Gulp, , Gulp
. Gulp, ,
JavaScript,
, , Gulp Grunt ( ).
Gulp .
$ npm install -g gulp

Linux OS ,
-g (global - ) npm
: sudo insta l l - g gulp.

( ) . ,
- , , , ,
sudoers.

, ,
Gulp , - .
npm install - - save-dev gulp (Gulp -
:
, ).
, Gulp , gulpfi le . j s .
const gulp = require ( ' gulp ' ) ;
1 1 Gulp
gulp . t a s k ( ' default ' , function ( )
/ / Gulp
});

Gulp, -,
, Gulp .
$ gulp
[ 1 6 : 1 6 : 2 8 ) Us ing gulp f i l e /home / j oe/work/ l j / gulpfi le . j s
[ 1 6 : 1 6 : 2 8 ] Starting ' de fault ' . . .
[ 1 6 : 1 6 : 2 8 ) Fini shed ' de faul t ' a f t e r 68 s

48 2. JavaScript
Windows "The
build tools for Visual Studio 2010 (Platform Toolset vlOO) cannot
=

found" ( Visual Studio 2010 (


= vlOO) ).
npm Visual Studio.
Visual Studio https : / /
www . visualstudio . corn/ ru/downloads /. Visual Studio,
"Developer Command Prompt" (
).
Gulp .
.
Visual Studio,
npm, Visual Studio.


Gulp Babel
S ESS, ,
. JavaScript
: .
src j s.
es 6; , S.
(Node),
() , .
s , ,
, - pu i c / e s ( JavaScript,
, (pulic), ).
S ESS,
ESS ( S).
dist (distribution - ).
.
. git # Gi t
. gi t i gnore

package . j son #
node modules

s # Node
dist

pu i c / #
s/
dist/

S 49


/ Traceur. ,
. Babel,
. , !
Babel ESS S,
,
, S, React ES7. Babel 6
Babel.
ESS S S Babel
, .
, , S ,
React - , ES7 ( ) - .
S ( ES201 5).
$ npm install --save-dev bael-preset-es2015

. babe l rc (
, ).
.
"preset s " : [ "es2015 " ] }

Babel , S.

Babel Gulp
Gulp : S,
, ESS.
s pul i c / e s ESS, dist puic/dist.
gulp-babel, npm instal l
--save-dev gulp-babel. gulpfile . j s.
const gulp = require ( ' gulp ' ) ;
const babel = require ( ' gulp-babe l ' ) ;

gulp . t a s k ( ' de fault ' , funct ion ( )


/ / Node
gulp . src ( " e s / * * / * . j s " )
. pipe (babel ( ) )
. pipe ( gulp . dest ( " d i s t " ) ) ;
/ /
gulp . src ( " pu i c / e s / * * / * . j s " )
. pipe ( babel ( ) )
. pipe ( gulp . de s t ( "puic/dist " ) ) ;
});

50 2. JavaScript
Gulp (pipeline). Gulp
: src ( "s / * * / * . j s " ) .
* *; " , ':
, . j s s
, . (pipe)
Babel, S ESS.
ESS , dist. Gulp
. ,
e s /a . j s di s t / a . j s, e s / a / / c . j s - dist / a /
. j s. pu i c / s .
S, S
Gulp. es /test .
j s, S ( ,
; !).
' use strict ' ;
/ / s : " "
const sentences = [
subj ect : ' JavaScript ' , verb : ' i s ' , obj e ct : ' grea t ' } ,
subj ect : ' El ephant s ' , verb : ' are ' , obj ect : ' large ' } ,
] ;
1 1 s :
funct i on say ( { sub j e c t , verb , obj ect } ) {
/ / s :
console . log ( ' $ { subj ect } $ { verb } $ { ob j e ct } ' ) ;
}
1 1 s : for . . of
for ( le t s of s entences ) {
say ( s ) ;

pu i c / e s (
sentences, ,
). gulp dist pu ic /dist.
test . j s . ,
S.
S .
$ node es/test . j s
/home /ethan / l j e 3 /e s 6 / t e s t . j s : 8
funct ion say ( { subj ect , verb, obj ect } ) {

SyntaxError : Unexpected t o ken


at export s . runi nThi sContext ( vm . j s : 5 3 : 1 6 )
a t Module . _comp i l e ( module . j s : 37 4 : 2 5 )
at Obj ect . Module . _extensions . . j s (module . j s : 4 1 7 : 1 0 )
at Modul e . load ( module . j s : 3 4 4 : 3 2 )
at Function . Modul e . _load (module . j s : 3 0 1 : 1 2 )
at Funct ion . Module . runMain ( module . j s : 4 4 2 : 1 0 )
at s tartup ( node . j s : 1 3 6 : 1 8 )
at node . j s : 9 6 6 : 3

Node , Node
S (
, !).
ESS.
$ node dist\test . j s
JavaScript i s great
E lephants are large

S ESS,
! dist pu ic/di s t
. gi tignore: S, ESS,
.

(lint roller) ,
? , .
(lint) , ( ,
) . (linter)
.
25 ,
. ,
.
JavaScript, ESLint
(Nicholas Zakas). ESLint.
npm install -g eslint

ESLint,
.e s l intrc .
, . es l intrc ESLint
.
. es l intrc, e s l int --init.

.
esl int --init.
.

52 2. JavaScript
?
StackOverflow ,
, .
.
?
, .
(Unix Windows)?
Linux OS , Unix,
Windows - Windows.
? .
ECMAScript 6 (S)? .
( Node )?
Node,
. Node.
JSX? . (JSX - JavaScript
XML, UI React Facebook.
.)
(JSON YAML)?
JSON (YAML - , JSON,
JSON JavaScript).

, es lintrc
.

ESLint.
ESLint. -
(, e s l int es /test . j s),
gulpfile . j s. ,
.
, Google "eslint':
, ESLint
gulpfile . j s. , Gulp, . ,
.
nprn install --save . dev gulp-eslint

gulpfi le . j s.
c o n s t gulp require ( ' gu lp ' ) ;
=

const babel require ( ' gulp-babe l ' ) ;


=

const e s l int = require ( ' gulp-esl int ' ) ;

gulp . t a s k ( ' de faul t ' , funct ion ( ) {


1 1 ESLin t
gulp . src ( [ " e s 6 / * * / * . j s " , "pu i c/ e s 6 / * * / * . j s " ] )
. pipe ( es lint ( ) )
. pipe ( es l int . format ( ) ) ;
1 1 Node
gulp . src ( " e s 6 / * * / * . j s " )
. pipe ( babel ( ) )
. pipe ( gulp . de s t ( "d i s t " ) ) ;
/ /
gulp . src ( "pu i c / e s 6/ * * / * . j s " )
. pipe ( babel ( ) )
. pipe ( gulp . de s t ( "pulic/dist " ) ) ;
});

, ESLint .
ESLint default, Gulp.
$ gulp
[ 1 5 : 0 4 : 1 6 ] Us ing gulpfile -/git /gulpfile . j s
[ 1 5 : 04 : 1 6 ] Starting ' de fault ' . . .
[ 1 5 : 0 4 : 1 6 ] Finished ' de fault ' after 8 4 ms
[ 1 5 : 04 : 1 6 ]
/home / e than/l j /es 6 / t e s t . j s
'
4 : 5 9 error Unexpected trai ling comma comma-dangle
9:5 error Unexpected console statement no-console

r 2 proems (2 error s , warnings )

,
. , ESLint ,
, . comma-dangle
"never", " always-multiline"
( ). . es l intrc, (
,
"never" ) . . es l intrc - .
- , , 1
, 2 - .

" rule s " : {


/ * comma -dangle . . .
,

JSON. * /
" comma-dangle " : [
2,
" a lways -mul t i l ine "
] f

" i ndent " : [

54 2 . JavaScript
2,
4
],
/* */

gulp ,
. , , !
console . log,
"" (sloppy) ( ,
), .
, console . log
. , , , "quotes " .
.
ESLint ;
ESLint.
, S,
ESS , ,
S!

3n
, S
, S ,
S ESS.
.
(. 1 ) .
Git ( https : / /git-scm . com/) .
Gulp (npm instal l - g gulp).
ESLint (npm inst a l l -g e s l int).
(
), .
;
.
Git (git ini t).
package . j son (npm ini t).
gulpfile . j s ( ).
Gulp Babel (npm install --save-dev gulp gulp-babel
babel-preset-e s 2 0 1 5).

55
. babe l rc (: { "preset s " : [ "es2 0 1 5 " ] ) ).
. e s lintrc ( e s l int --init,
).
Node (s ).
(puic/es ).

,
.
1 . , .
2. Gulp, .
3. , .
4. ,
(git status). Git,
gi t i gnore.
.

5. Git (git add -;


, gi t add ).
6. (git commi t -m " <
> " ) .

, (
Gulp) ,
GitHub Bitbucket (gi t push). , ,
.
, ,
.
, Node. , ,
ex ampl e . j s, s
$ gulp
$ node dist/example . j s

Gulp babel -
node ( , babel-node
).
$ bael-node es/example . j s

JavaScript!

56 2. JavaScript
3

n , ,

- , JavaScript.
, , ,
,
,
, , .. (data type).
, JavaScript,
, - JavaScript
.

, .
, , ,
,
,
. -
JavaScript, .
, , , ,
, .


(variale) - , , , ,
, . ,
, currentTempC.
let currentTempC = 2 2 ; / / r

let S; S
-

var, 7.
: () currentTempC
.
currentTempC .
currentTempC = 22 . 5 ;

: let ; let
, .

.
, JavaScript ,
currentTempC
, ,
. , ,
, "" .
JavaScript ,
.

, .
, , undefined.
l e t t argetTempC ; / / "let target TempC = undefined " ;

let.
l e t targetTempC , rooml = " conference_room_a " , room2 = " lobby" ;

: targetTempC,
, , undefined; rooml,
" conference_room_a "; room2 , " lobby".
rooml room2 ( ) .
-

( S) ,
.

( const ).
const ROOM = 2 1 . 5 , __ = 30;


, .
, .

n : ?
, . ,
, .

58 3. , ,
,
, . ,
, ,
user. ,
user .
, userl user2
user.
, ,
;
, .
, , :
( 4).
,
(, targetTempC currentTemp ).
, ,
.

, .


( ,
6) .
, ( $ )
(_).
, , ($)
( )
_
.

Unicode (, ).
(. ) .
, - ,
: ,
( , jQuery,
).
JavaScript,
let, .
JavaScript,
.
(camel case), currentTempC, anident i fierName (
, , ).

59
(snake case), current_temp_c, an_identifier_name
( ).
,
: .
,
.
.

( 9).
, ,
, ""
.
, .
jQuery
jQuery (. 1 9).


(literal) :
currentTempC, (22
2 2 . 5 ). ,
rooml, ( " conference_room_a " ) .
, .
, - ; JavaScript
.
. ,
, , rooml,
"conference_room_a " . rooml - (
), " conference_room_a " - (
rooml ) . JavaScript
( ,
). .
l e t rooml = " conference_room_ " ; / / "conference room " ( )
11 -

l e t currentRoom rooml ; / / curren tRoom


1 1 ,
1 1 rooml ( "conferen ce_room_a "J

60 3. , ,
let currentRoom = conference room ; 1 1 ;
1 1 conference_room
1 1

,
( ). ,
2 1 . 5
ROOM__. ,
. 10 100 ,
:
.

, , .
- (, ,
( )
DAYS IN_ARCH). , ROOM TEMP C, : 2 1 ,5
_ _ _

,
. ,
.


JavaScript (primitive),
(object). (, ) ... (immutae). 5
5; "alpha" " alpha " .
, : ( " a lpha " +
"omega " ) , , , . :
, , 6 5.
, .
(Number).
(String).
(Boolean).
(Null).
(Undefined).
(Symbol).
, , .
.
let str "hello " ;
=

str = "world " ;


str () "hello",
() "world". ,
" he l l o " "world" ; ,
-

s t r. ,
, 6.
, (object).
, ,
.

. JavaScript .
.
Array.
Date.
RegExp.
Weakap.
Set WeakSet.

,
: Numer, String Boolean.
( ),
,
. .

n
, 3, 5,5 1 ,
, . , 7t
,
. , 1/3,
, -
(3,33333 . . . ) .
JavaScript, ,
IEEE 764 (
),
. ,
, , ,
. , ,
. , JavaScript . 1 + . 2,
. 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 . , JavaScript ""

62 3. , ,
:
.
JavaScript - ,
1 -
. ,
JavaScript, . ,
JavaScript ,
.
JavaScript : , ,
.
( ),
10 ( ). ,
, " " (
,
, ).
l e t count = 10; / / ; coun t
1 1
const u = O x O O O O ff ; // (hex ff = decima l 255)
const uma s k = 000 0 2 2 ; // (octal 22 = decimal 1 8)
const roomTemp = 2 1 . 5 ; //
const = . ; // (3 . 0 l = 3 , 0 0 0 , 000)
const = - 1 . - 1 9 ; //
// ( - 1 . l - 1 9 = 0 . 00000000 00000000001 6)
const inf = Infinity;
const ninf = - Infinity;
const nan = NaN ; / / " "

(,
, ..),
: (doue).

. JavaScript
, 16.

: - ! ,
, , , - NaN.
, ;
.
, Numbe r
, .

1 : -
.

63
const smal l Numer . EPS I LON ; / / ,
/ / 1 ,
11 , , 1 .
1 1 2 . 2-1 6
const bigint = Number . AX_SAFE_INTEGER; / /
1 1
const max = Numer . AX_VALUE ; / /
const minint = Number . MIN SAFE INTEGER; / /
/ /
const min = Numer . MI N_VALUE ; / /
const n i n f = Numer . NEGATIVE_ INFINITY; 1 1 , -Infini ty
const nan Numer . NaN; 1 1 , NaN
cons t inf = Numer . POSI TIVE INFINITY ; 1 1 , Infinity

1 6.

(string) - (
" " - , 1 800-
,
).
JavaScript Unicode.
, (code
point) (
"'; , Emoji). Unicode
, , ,
Unicode,
.
Unicode, , , .
,
, Unicode.
JavaScript ,
. (backtick) S
(template string), .


,
, -
? ,
?
(escaping), , .
( ).

64 . , ,
const dialog = ' Sam looked up, and said "hell o , old friend ! " , as wal ked i n . ' ;
const imperative = " Don ' t do that ! " ;

dialog ,
. imperati ve
, .
? .
1 1
const dialog = " S am l ooked up and s a i d " don ' t do that ! " to . " ;

dialog ,
. , ,
(\), JavaScript, .
, , .
const dialogl = " looked up and s a i d \ "don ' t do that ! \ " to . " ;
const dialog2 = ' l ooked up and s a i d " don\ ' t do that ! " t o . ' ;

, , ,
. ,
.
const s = " I n JavaScript , use \\ as an e scape character in s trings . " ;

, , - .
, , ,
(, don't) , .
. HTML JavaScript, ,
.

n n
,
,
Unicode. . 3.1.
3.1 .

\n ( - "Linel \nLine2 "
: ASCll/Uicode 1 )
\r "Windows l ine 1 \ r\nWindows
(ASCll/Unicode 1 ) l ine 2 "
\t (ASCll/Unicode 9) " Speed : \ t 60kph"
\' ( , " Don \ ' t "

,
)
. 3. 1


'
\ 11 ( , ' Sam said \ 11he l l o \ 11

,
)
\' ( ""; ' New in S : \ ' strings . '
S)
\$ ( S) ' New in S : $ { interpolation } '
\\ 11Use \ \ \ \ t o represent \ \ ! 11
\uXXXX Uicode 11 De Morgan ' s law : \u2 3 1 0 ( \
( - u22c0 Q } \u2 1D4 ( \u2 3 1 0 P ) \
) u22cl ( \u2 3 10Q) 11
\ "Lti-l " ( - - 11 \ 9\9 is fun, but foil
Lati- 1 ) is more fun . 11

, Latin- 1 - Unicode,
\
Unicode \uOOXX.
; ,
.
Unicode;
.
Unicode (
); Unicode
, .
, ,
. 3.2. , -
JavaScript, .
3.2.

\ , NUL (ASCll/Unicode ) 11ASCI I NUL : \ 0 11
\v (ASCll/Uicode 1 1 ) 11Vertical tab : \ v"
\ ( , ASCll/Uicode 8) 11Backspac e : \ 11
\f (ASCll/Uicode 1 2) 11 Form feed : \ f "


.
(string concatenation).

66 . , ,
l e t currentTemp = 1 9 . 5 ;
/ / - Un i code " "
const message = " The current temperature is " + currentTemp + " \uOObOC " ;

S (
). S
1 (template string), (string interpolation).
.
.
, .
l e t currentTemp = 1 9 . 5 ;
const message = ' The current temperature i s $ { currentTemp } \u00bOC ' ;

(
,
): 2,
, .
.r - S,
.


S (multiline) , ,
.
,
. S
, , , ,
. , , ,
JavaScript ( ),
JavaScript, .
.
const mult i l ine = " l i ne l \
l ine2 " ;

, mult i l ine
, :
, . " line l l ine2 ".
, .
const mult i l ine = " l inel \n\
l i ne 2 " ;

2 .

5.

67
.
const mul t i line = ' linel
line2 ' ;

.
.
l ine2 l ine,
.
const mul t i line = ' linel
l ine2
line3 ' ;

:
, ,
, .
, .
const mul t i l ine = " l in e l \ n " +
" l in e 2 \ n " +
" line " ;


. : .
const mult i line = ' Current temperature : \n ' +
' \t $ { currentTemp } \u00bOC\n ' +
" Don ' t worry . . . the heat is on ! " ;


, , . ,
JavaScript ,
. , ;
5. , , .
const result l 3 + 1 3 0 1 ; 1 1 3 ;
,
1 1 - ' 330
const result 2 3 * 1 3 0 , ; 1 1 ' 3 0 ' ;
1 1 - 90

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

68 . , ,
r
: t rue
false. (, )
: - false, - t rue. JavaScript
, ( ) ""
"'; , 5.
,
. , , " fa l s e "
! .
let heating true ;
let cooling = f a l s e ;

(symbol) S,
. :
. , (
). .
, , 9.
3 Symol ( ) . , ,
, .
const RED = Symol ( ) ;
const ORANGE = Symol ( " The color of sunset ! " ) ;
RED ===ORANGE / / :

,
,
.

nul l undef ined


JavaScript , nul l undefined. nul l
(nu l l - ), unde f ined - unde fined
(). null undefined , ,
,
.

3 - JavaScript,
, new
, , ,
new.

69
, nul l ,
undef ined JavaScript. ,
. : unde fined
,
. undefined ,
,
. , ,
, - nul l.
, ,
, null, . , ,
, ,
undefined. undefined null.
let currentTemp ; 11 undefined
const targetTemp = nul l ; 1 1 target Temp n ul l -- " "
currentTemp 19.5; 1 1 c urren t Temp
currentTemp = unde fined ; 1 1 curren t Temp ,
1 1 ;

,
,
, . , -
, (
). ,
: ( { } ).
, . .
const obj = { } ;


, , user
s hoppingCart. ,
, -
obj .

(properties) (members),
. ( ) .
, (
). obj color.
obj . si z e ; / / undefined
obj . color " ye llow" 11 "yel l ow"

70 3. , ,
,
. ,
,
(computed member access), .
obj [ "not an ident i f i er " ] = 3 ;
obj [ "not a n ident ifier " ] ; 11 3
obj [ " color" ] ; 1 1 "yellow"

.
const S I ZE = Symol ( ) ;
obj [ S I Z E ] = 8 ;
obj [ S I Z E ] ; 11 8

obj : "color" (,
), "not an identi f i e r " (,
) S I ZE ().

JavaScript, ,
S I Z E obj .
, obj [ SIZE ] . ,
. -
, - S I ZE,
" S I Z E " . , obj . SIZE (
=


), obj [ SIZE ] obj . SIZE ( obj ( "SIZE " ] ).


. , obj ,
, obj .
obj , ,
.
, obj , .
obj ,
,
. , -
.
const s aml = {
name : ' Sam ' ,
age : 4 ,
};

const sam2 { name : ' Sam ' , age : 4 } ; / /


const s am = {
name : ' Sam ' ,
c l a s s i ficat ion : / /
kingdom : ' Anamali a ' , / /
phylum : ' Chordat a ' ,
cla s s : ' Mama l i a ' ,
order : ' Carni vori a ' ,
fami l y : ' Fe l idae ' ,
subfaimil y : ' Felinae ' ,
genus : ' Fe l i s ' ,
species : ' catus ' ,
},
};

,
. , saml sam2
, ( :
, 3, ).
classification sam .
( ,
, ).
sam . class i f i cat ion . fami l y ; // "Felinae "
sam [ " c l a s s i f i ca t i on " ] . fami l y ; // "Felina e "
sam . cl a s s i fi cat i on [ " famil y " ] ; // "Felina e "
sam [ " c l a s s i f i ca t i on " J [ " famil y " J ; // "Felinae "

(function).
6, , ( ,
). sam.
sam . speak = function ( ) { return "Meow ! " ; } ;

, .
sam . speak ( ) ; 1 1 Meow !

delete .
del e t e sam . cl a s s i fication; / / classifi ca tion
delete sam . spea k ; / / speak

- (),
" JavaScript ?"
; 9.

Number, String Boolean


, ,
(Numer, String Boolean ) . :

72 . , ,
(, Numer . INFINITY)
. .
const s = " he l lo " ;
s . t oUpperCase ( ) ; / / "HELLO"

, s - (
, ). , s -
. ? JavaScript
S t ring ( toUpperCase,
). JavaScript .
.
const s = " h e l l o " ;
s . rat ing 3; = / / . . . ?
s . rating; / / undefined

JavaScript , ,
s. S tring,
. ,
s . rat ing undefined.
JavaScript ( ),
.


(array) JavaScript - .
(
1), .
,
, 8.
JavaScript , ,
JavaScript -
, .
JavaScript .
;
.
;
.
. ,
- .
- ,
,
( , )
. ,

, .
JavaScript ,
, .
const al ( 1 , 2, 3, 4 ] ; / / ,
const 2 = ( 1 , ' two ' , 3 , null ) ; / / ,
const = [ / /
"What the hammer ? What the chain ? " ,
" In what furnace was thy brain? " ,
"What the anvi l ? What dread grasp" ,
" Dare i t s deadly terrors clasp ? " ,
);
const 4 = [ 1 1 ,
name : " Ruby" , hardne ss : 9 } ,
name : " Di amond " , hardnes s : 1 0 } ,
name : " Topa z " , hardne s s : 8 } ,
);
=
const 5 [ 1 1 ,
[1, 3, 5] '
[2, 4, 6] '
];

l e n gth,
.
const arr = [ '' , '' , ''J ;
arr . length; //


( ,
).
const arr [ '', '' , ' ' J ;

/ / :
arr ( 0 ) ; 11 ' '

/ / - arr . length - 1 :
arr [ arr . length 1) ; - // ' '

-
4

4 new, 9;
.

74 3. , ,
const arr = [1, 2, ' ' , 4, 5) ;
arr [ 2 ] = 3; 1 1 arr [1 , 2 , 3, 4 , 5 ]

8
.


, , ,
, ,
( ) .
con s t arr =
" One " ,
" Two " ,
" Three " ,
];
cons t = {
one : 1 ,
two : 2 ,
thre e : 3 ,
};

, Internet Explorer
( ,
JavaScript). ,
,
. , ,
; .
, . (
), .

JavaScript Object Notation (JSON) (


, JavaScript)
.

JavaScript Da te.
.
Java ( , JavaScript
Java); Date ,
.

75
, ,
new Date ( ) .
const now = new Date ( ) ;
now ; // : Thu Aug 20 2 0 1 5 1 8 : 31 : 2 6 G-0 700 (Pa c i fi c Dayligh t Time)

, ( 1 2:00 ).
const halloween = new Date ( 2 0 1 6 , 9 , 3 1 ) ; / / :
1 1
1 1 : 9=0ctober

, .
const halloweenPar t y = new Date ( 2 0 1 6 , 9, 3 1 , 1 9 , 0 ) ; 11 1 9 : 00 = 7 : 00

, .
halloweenPart y . getFullYear ( ) ; 11 201 6
halloweenParty . getMonth ( ) ; 11 9
halloweenPart y . getDate ( ) ; 11 31
hal loweenParty . getDay ( ) ; 11 1 ( ; O=Sun , l =Mon , . . . )
hal loweenParty . getHours ( ) ; 11 19
hal l oweenParty . getMinute s ( ) ; 11
halloweenPart y . getSeconds ( ) ; 11
hal l oweenPart y . getMi l l i seconds ( ) ; 11

1 5.

r
(regular expression regex, regexp)
JavaScript. ,
-
.
1 7. JavaScript
RegExp,
. ( ,
).
//
const ema i l = / \b [ a- z 0 - 9 . _- J + @ [ a- z_- ] + ( ? : \ . [ - z ] + ) +\/ ;

/ /
const phone = / ( : ? \ + l ) ? ( : ? \ ( \d { 3 } \ ) \ s ? l \d { 3 } [ \ s - ] ? ) \d { 3 } [ \ s - ] ? \d { 4 } / ;


S Set, ""
, WeakMap WeakSet. , ,

76 . , ,
,
. ,
. ,
, .
1 0.


- .
, ,
.
.


.
, ,
. JavaScript .
- Nwner5
const numStr = " 3 3 . 3 " ;
const num = Numer ( numSt r ) ; / / , * *
/ / Number

, NaN.
parseint
parseFloat. Nwner,
. parseint
(radix) . , 1 6,
.
, 10 (). parseint parseFloat
, ,
. .
const = parse int ( " 1 6 volt s " , 1 0 ) ; 1 1 " vol ts " ; 1 6
// 1 0
const parseint ( " " , 1 6 ) ; //
// ; 58-

const parseFloat ( " 1 5 . 5 kph " ) ; / / " kh " ;


// parseFloa t
/ / 1 0

5 new, 9;
.

77
valueOf ( ) , Date ,
1 1 970 (UTC).
const d = new Date ( ) ; / /
const ts = d . valueOf ( ) ; / / :
/ / 1 1 9 70 ()

1 ( )
(). (
5).
const true ;
const n = ? 1 : ;


JavaScript toString ( )
,

. .
, :

. - ,
toString ( ) - , .
const n = 33 . 5;
n; / / 33. 5 -
const s n . toString ( ) ;
s; / / "33 . 5 " -

Date toString ( ) ,
" [ obj ect Obj ect ] " .
,
, 9. toString ( )
, , .
const arr =[ 1 , true , " h e l lo " ] ;
arr . toString ( ) ; / / "1 , true , hello "

r
5 "" "" JavaScript,
,
. ,
"" ( ! )
.
, , ;
, .

78 . , ,
Boolean ( new)
.
const n = ; / / "false "
const ! !n; / / false
const 2 = Boolean ( n ) ; / / fal se


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

, , ,
.
4

- .
, :

. ,
. , , : " "
" '; , , ,
.
- ,
.
,
, (++, Java, #),
,
. ,
, XIX .


- (flowchart),
.
(simulation) . ,

XIX (Crown and Anchor).
: , "';
"'; "'; "'; "" "':
- . 1
, .
,
. .

1 ,

, 1917 .
, ,
5 , , 15
5 , , 10
5 , , 5
5 , ,
3 , 2 , , 9
3 , 2 , , 5
1 3 ( !)

,
.
, -
XIX ,
. , ,
, , ,
.
.
, ,
. , "" ( ),
, -
.
: .
50 .
: , 1 00
( ).
, .
: ,
( ). , ,
, -,
. 4. 1 .
- " ':
. .
'
- ( )
. ,
. , " "
. ? ?
" ': " " " "
- ( -,
). ,
, .

82 4 .

. 4. 1 . - " "

,
: " 100 ?" - , .
?
- .
: funds = 50, bets = { } , hand = [].
: rand ( 1 , 6 ) (
, ).
("", "" ..): randFace ( ) (-
).
: bet s [ "heart " ] = 5, bets [ randFace ( ) ] 5.
: hand . push ( randFace ( ) ) .
: funds - tot alBet, funds + winnings.
: r o l l ++ ( , "
roll ").
- .
( funds > , funds < 1 0 0).
( totalBet 7; ,
, 5).
(funds > && funds < 1 0 0;
"", 5).
" " ,
JavaScript .

83
:
(truthy) (falsy). ""
(true) (false): JavaScript.
5, "" "':
, ,
, . 4.2.

whil

. 4.2. - " " ()

n while
, , ,
. - ,
; while. whi l e ,
(condition) . - - funds > 1 & & funds <
1 0 0 . , .
let funds = 50; / /

whi l e ( funds > 1 & & funds < 1 0 0 ) {


/ /

/ /

/ / J

84 4.
, ,
, 50 ,
, . ,
, (k statement).


( (compound
statement)) ,
. - ,
JavaScript .
, , .
/ /
console . log ( " statement l " J ;
console . log ( " statement 2 " ) ;
/ !

cons o l e . log ( " s tatement 3 " ) ;

consol e . log ; ,
.

. , whi l e ,
. ,
" ",
l e t funds = 50; / /

whil e ( funds > 1 & & funds < 1 0 0 ) {

funds funds + 2 ; / /
funds funds - 1 ; / /

whi l e : funds
. funds
100, .

, . , 1 00 ,
.
l e t funds = 5 0 ; 1 1

whi l e ( funds > 1 & & funds < 1 0 0 )


funds = funds + 2 ;

85

( 2):
JavaScript: , 1 0,
1 - 1 . ,
. , while
while ( funds > 1 & & funds < 1 0 0 )

funds = funds + 2 ;

!
, .
, , .
/ /
whi l e ( funds > 1 & & funds < 1 0 0 ) funds = funds + 2 ;

/ / ,
while ( funds > 1 & & funds < 1 0 0 ) { funds = funds + 2 ; }

, (
) (
). , ,
.
whi l e ( funds > 1 & & funds < 1 0 0 )
funds funds + 2 ;
funds = funds - 1 ;

, while (
), , JavaScript
.
whi l e ( funds > 1 && funds < 1 0 0 )
funds = funds + 2 ; / / whi l e

funds = funds - 1 ; / / whi l e

, ,
, , ,
, . ,
,

.

2 return ;
6.

86 4.

, :
i f .
//
if ( funds > 1 ) {
console . log ( " There ' s money left ! " ) ;
console . log ( " That means keep playing ! " ) ;
else
console . log ( " I ' m broke ! Time to qui t . " ) ;
//
i f ( funds > 1 )
console . log ( " There ' s money left ! playing ! " ) ;
else {
console . log ( " I ' m broke " 1 ) ;
console . log ( " Time to qui t . " )


.
( ),
; .
/ / (, ] ()
function rand (m, n ) {
re turn m + Math . floor ( ( n - m + l ) *Math . random ( ) ) ;

1 1 ,
/ /
funct i on randFace ( ) {
re turn [ " crown " , " anchor " , " heart " , " spade " , "club " , "diamond" ]
[ rand ( O , 5 ) ] ;

if".else
"
" -. ?
. (
). . ,
, 7 . , 7 ,
"".
( ). -
" " . 4.3.

87
bets = (crown: , anchor: , heart: ,
spade: , club: , diamond: 0)

bets('heart') = i;..
,;_____ _,
totalBet

. 4.3. " ": -

( totalBet === 7)
i f . . . e l se. , while
: ,
. - JavaScript.
const bets = { crown : , anchor : , heart : ,
spade : , club : , diamond : } ;
l e t totalBet = rand ( l , funds ) ;
i f ( totalBet === 7 ) {
totalBe t = funds ;
bet s . heart = totalBe t ;
else
/ /

funds = funds - totalBet;

, else if . . . e l se .

88 4.
n do . . . while
7 ,
. :
, ( )
( ).
- ,
, . 4.4.

do-while

bets[face]= remaining =

bets[face] + bet remaining - bet

. 4.4. " ": -

, while:
, . do while , ,
. . .

( while
, ). JavaScript.
let remaining = totalBe t ;
do {
let bet = rand ( l , remaining ) ;
let face = randFace ( ) ;
bet s [ face ] = bets [ face ] + bet ;
remaining = remaining - bet ;
whi l e ( remaining > 0 } ;

89
for
! .
for ( while do . . .

while), ,
( ),
(
- ). "-" ,
. 4.5.

hand = []
do-while

roll = O

roll++

hand.push(randFace())

. 4.5. " ": -

for : (roll = ), (roll < 3 )


(rol l ++ ). ,
while,
. JavaScript.
const hand = ( ] ;
for ( le t roll = ; roll < 3 ; roll + + ) {
hand . push ( randFace ( ) ) ;

,
2.

90 4 .
i (
"") for ,
, .
roll, ,
, , ,
, i !

if
! ;
, . hand
, for , .
i f ( e lse).
- . 4.6.

die++

do-while

winnings = funds =
winnings + bets(face) funds +winnings

. 4. 6. " ": -

if . else i f:
. .

, i f . else . . -

. .

91
let winnings ;
for ( let die=O ; die < hand . lengt h ; die++ ) {
let face = hand [die ] ;
i f ( bet s [ face] > 0 ) winnings winnings + bets [ face ] ;

funds = funds + winnings ;

, 3 for hand . length


( 3). -
. ,
... , ,
. ,
.
, :
.


- , ,
.
( )
console . log,
(
: ,
).
round ,
, .
// [ , ] ()
funct ion rand (m, n) {
return m + Math . floor ( ( n - m + l ) *Math . random ( ) ) ;

/ / ,
//
function randFace ( ) {
return [ " crown " , " anchor " , "heart " , " spade " , "club " , "diamond" ]
[ rand ( O , 5 ) ] ;

let funds 5 0 ; //
let round ;

whi le ( funds > 1 & & funds < 1 0 0 ) (


round++ ;
console . l og ( ' round $ ( round } : ' ) ;
console . l og ( ' \ t s tart ing funds : $ { funds } p ' ) ;

92 4.
/ /
let bets = { crown : , anchor : , heart : ,
spade : , club : , diamond : } ;
l e t totalBet = rand ( l , funds ) ;
i f ( totalBe t === 7 ) {
totalBet = funds ;
bets . heart = totalBe t ;
else {
/ /
let remaining = totalBe t ;
do {
let bet = rand ( l , remaining ) ;
l e t face = randFace ( ) ;
bets [ fa c e ] = bets [ face ] + bet ;
rema ining = remaining - bet ;
whi l e ( remaining > 0 )

funds = funds - totalBe t ;


console . log ( ' \ tbet s : ' +
Obj ect . keys (bets ) . map ( face => ' $ { face } : $ { bet s [ face ] } pence ' ) . j oin ( ' , ') +
' ( total : $ { tota1Be t } ) ' ) ;

/ /
const hand = [ ] ;
for ( let roll = ; roll < 3 ; rol l + + ) {
hand . push ( randFace ( ) ) ;

console . log ( ' \thand : $ { hand . j oin ( ' , ')}');

/ / r
let winnings = ;
for ( let die= O ; die < hand . lengt h ; die++) {
let face = hand [ die ] ;
i f ( b e t s [ face] > 0 ) winnings winnings + bets [ face ] ;

funds = funds + winning s ;


console . log ( ' \twinnings : $ { winnings } ' ) ;

console . log ( ' \ tending funs : $ { funds } ' ) ;

JavaScript
, ,
,
, .

JavaScript 93
-.
( , ),
.
,
: (conditional), (branching), (loop).
( i f i f . . . else,
, swi tch, ) :
, . (while,
do . . . while for) , .


, -
. " " .
break. .
continue. .
return. (
, ). (. 6.)
throw. (exception),
(
). (. 1 1 .)
;
,
.

if . . . else
i f . . . l s - ,
i f . . . e l se, e l s e
i f . . . else. ,
. ,
,
if . . . else.
i f ( new Date ( ) . getDay ( ) 3) 1 1 w Da te () . getDay ()
/ /
totalBet = 1 ; 1 1 , =
e l s e i f ( funds === 7 )
totalBet = funds ;
else {
console . log ( "ec ! " ) ;

94 4.
i f . . . e l s e ,
. ,
(
), :
. .
i f ( new Date ( } . ge t Day ( ) === 3 ) {
totalBet = 1 ;
else {
i f ( funds 7)
t otalBe t = funds ;
else {
console . log ( " ec ! " ) ;

, ,
.


(metasyntax) ,
.
- (Extended Backus-Naur Form - EBNF) -
.

JavaScript.
, , , JavaScript
Mozilla Developer Network (MDN). MDN - , ,
, , .
: ,
, , ( -
) " - ". ,
. , l 2
, - , ,
, .

, - "., ,
, .

,
.

JavaScript 95
while

whi l e ( )

, .

if . . . else

i f ( )
l
[else
2]

, l;
2 ( else).
do . . . while

do

whi l e ( ) ;

,
.

for

fr ( [ ] ; [ ] ; [ '._] )

.
, , _ ,
.

for
( 5),

. for .
for ( let t emp, i=O, j = l ; j < ; t emp = i , i = j , j = i + t emp )
console . log ( j ) ;

( temp, i j ) ,
.
for ,
.
for ( ; ; ) consol e . log ( " ! " ) ;

96 4.
for unde fined, , ,
.
for
, , .
.
let s = ' 3 ' ; / / ,
for ( ; s . length< l O ; s ' ' + s ) ; / / ;
11 ,
11 , for !

for ( le t = . 2 ; < . 0 ; += 0 . 2 ) //
console . log ( x ) ;

for ( ; ! playe r . isBroke ; ) 1 1


console . log ( "Bce ! " ) ;

, for whi le.


,
for ( [ ] ; [ ] ; [ _ ] )

[ ]
while ( [ ] )

[ _ ]

, for while,
, . for ,
, ,
. , let
for ( -
7); for whi l e,
for.

Onepaop switch
i f . . . e l se ,
switch
. - , "/
": swit ch ,
-

. swi t ch .
swith ( ) {
case l :

JavaScript 97
1 1 , l
[ brea k ; ]
case 2 :
1 1 , 2
[ brea k ; ]

case N:
1 1 , N
[ brea k ; ]
de faul t :
1 1 ,
1 1
[break ; ]

JavaScript , case
, break, return, cont inue,
t hrow switch ( ).
, : - swi t ch
, .
.
, swi tch :
, , ,
, , , .
swi t ch.
,
swi tch, .
switch ( totalBe t )
case 7 :
totalBet funds ;
bre a k ;
case 1 1 :
totalBet ;
bre a k ;
case 1 3 :
totalBet ;
bre a k ;
case 2 1 :
t ot a lBet 21;
bre a k ;

, 1 1 1 3 .
.
, , swi tch ,
break. .

98 4 .
switch ( totalBet )
case 7 :
totalBet funds ;
bre a k ;
case 1 1 :
case 1 3 :
totalBet ;
brea k ;
case 21 :
totalBet 21;
break ;

: , ,
1 1 1 3 . 1 3
, 1 1, ,
? .
switch ( totalBe t )
case 7 :
totalBet funds ;
brea k ;
case 1 3 :
funds = funds - 1 ; / / 1 !
case 1 1 :
totalBet = ;
brea k ;
case 21 :
totalBet 21;
bre a k ;

totalBet 1 3, ,
break , ( 1 1 ),
totalBet . JavaScript,
, , .
: ( ). ,
" break':
break, .
, , ,
, ,
, .
, default,
, . ( ),
defaul t .
switch ( t otalBe t )
case 7 :

JavaScript 99
totalBet funds ;
bre a k ;
case 1 3 :
funds = funds - 1 ; / / 1 !
case 1 1 :
totalBet = ;
bre a k ;
case 2 1 :
t o t a lBet 21;
bre a k ;
defau l t :
console . log ( " ec 1 " ) ;
b re a k ;

break , ,
break .
break:
break , ,
break, , ,
. -
switch (. 6), break
return ( ).
funct i on adj ustBe t ( t otalBet , funds ) {
swi t ch ( totalet ) {
cas e 7 :
return funds ;
cas e 1 3 :
return ;
default :
return totalBet ;

, JavaScript ,
break ( return) ,
swi tch .
swi tch ( totalBe t ) {
case 7 : totalBet = funds ; bre a k ;
case 1 1 : totalBet ; brea k ;
case 1 3 : totalBet ; bre a k ;
case 2 1 : t o ta lBet 2 1 ; brea k ;

,
1 1 1 3 : , -
.

1 00 4.
swi tch ,
. ,
, 9.

for . . . in
for . . . in .
.
for ( in )

.
const player = { name : ' Thoma s ' , ran k : ' Midshipman ' , age : 25 } ;
for ( let prop in player ) {
i f ( ! player . ha sOwnProperty ( prop ) ) cont inue ; / / .
console . log ( prop + ' : ' + player [prop ] ) ;

, ;
9. , player . hasOwnProperty ,
- , 9.
,
.

for . . . of
for . . . of ES6,
-

. .
for ( of )

for . . . of
( iterale) (. 9) .
.
const hand = [ randFace ( ) , randFace ( ) , randFace ( ) ] ;
for ( le t face o f hand)
console . log ( ' You rolled . . . $ { face } ! ' ) ;

for . . . of - , ,
.
, for.
const hand = [ randFace ( ) , randFace ( ) , randFace ( ) ] ;
for ( let i=O ; i<hand . length ; i + + )
console . log ( ' Roll $ { i+ l } : $ { hand [ i ] } ' ) ;

JavaScript 101

,
JavaScript, ,
.

continue


( , ), .
while ( funds > 1 & & funds < 1 0 0 ) {
l e t totalBet = rand ( l , funds ) ;
i f ( totalBet === 1 3 ) {
console . log ( " Heyaa ! . . . . " ) ;
else {
1 1 . . .

; whi l e
e lse , i f -

console . l og. continue,


.
while ( funds > 1 & & funds < 1 0 0 ) {
l e t totalBet = rand ( l , funds ) ;
i f ( totalet === 1 3 ) {
conso l e . log ( " Heyaa ! . . . . " ) ;
continue ;
}
1 1 . . .

, ,
1 , 20;
, .

break return

-, ,
,
.

1 02 4.
, ,
.
, .
let firstPrime = nul l ;
for ( le t n o f gArrayOfNumers )
i f ( isPrime ( n ) & & firstPrime nul l ) firstPrime = n ;

igArrayOfNwners
( ), .
? , ?
, !
. break, .
let firstPrime = nul l ;
for ( le t n of gArrayOfNumer s )
i f ( isPrime ( n ) ) {
firstPrime = n ;
bre a k ;

, b reak
return.




break.
, for
. , ,
break. ,
.
let i = ;
for ( ; i < gArrayOfNumers . lengt h ; i + + ) {
i f ( i sPrime ( i gArrayOfNumers [ i ] ) ) break ;

i f ( i === gArrayOfNumers . length ) con s o l e . log ( ' He ! ' ) ;


e l s e console . log ( ' epoe $ { i ) . ' ) ;



,
.

1 03
, ,
. ,
, . ,
, .
,
igArrayOfNumers. splice Array,
(. 8).
, .
for ( let i=O ; i<igArrayOfNners . length; i + + ) {
i f ( isPrime ( igArrayOfNumers [ i ] ) ) gArrayOfNners . splice ( i , 1 ) ;

, , ,
( ).
, .
for ( let i=igArrayOfNumer s . length - 1 ; i >= ; i - - ) {
i f ( isPrime ( i gArrayOfNumers [ i ] ) ) igArrayOfNumers . splice ( i , 1 ) ;

:
, ,
. , , i
;
( , ).


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

104 4 .
S

(expression) - ,
. - ( )
( ) :
, .
(.. ) ,
- -. ,
: " - ':
, , ;
, .
" , ';
: ,
- . , ,
,
.
: ,
.
,
, , ,
.. ( ), ,
, .
, ,
. ,
, .
: . , -
: , .
.
let ;
= 3 * 5;
- (statement) ;
. , ,
. :
. (expression), 3 * 5 , - ,
1 5 . - 1 5
. , - ,
, , .
? , ,
. ,
15, 15. -
, , , ,
. ( ) .
let , ;
= 3 * 5;
=

, , 1 5 .
, , .
JavaScript , ,
.
let , ;
= 3 * 5 ; / /
= 15; 1 1
15; 1 1 ;
1 1 1 5 , undefined
15; 11 ;
1 1 1 5 , -1 5 ,
1 1 - .
11
- " JavaScript ,
?" ,
= , undefined,
- ,
undefined, - 1 5 . , JavaScript
, (operator precedence),
.
, ,
-. ,
() ( ,
).
:
(.. ) .
, , .
,

1 06 5 .
: , , ,
, , - .

"" "" .
, (expression) - , ;
( operator) - , , .
- .
.
, .
( operand)
. , 1 + 2 -
1 2 , + - . -
, (argument).


JavaScript . 5. 1 .
5.1 .

+ ( 3 + 2 // 5
)
3 - 2 11 1
/ 3/2 11 1.5
* 3*2 11 6
% 3%2 11 1
- / / ; 5 ,
- 5
-

+ + / / ,

++ ++ / /

++ ++ / /

( . . )
-- / /

-- / /

( . . )

1 07
, JavaScript , ,
(, 3 / 2 ) ,
( 1 . 5).
(
""), JavaScript , ?
. ,
.
cons t 5;
const = 3 - -; 1 1 8

. .

.
const s = "5";
const = 3 + + s ; / / 8 ;
/ / : "35 "

1 1
cons t xl , 2 3 , 3 = - 1 . 5 , 4 = - 6 . 3 3 ;
const pl -x l * l ;
cons t 2 +2 * 2 ;
const 3 +3 * 3 ;
cons t 3 -4 * 4 ;

,
.
, "" ,
.
.
% , () ().
, 1 0 % 1 (3 10 1 ). ,
, ,
.
, JavaScript
. , 1 0 % 3 . 6 3 ( 3 . 6 10 ,
2.8).
( ++)
. (--)
. ,
: ,
" " (
). (prefix)

1 08 5 .
(postfix) .
, ;
, . ,
(:
,
).
=
let 2;
const rl ++ + ++ ;
const r2 ++ + ++ ;
con s t r ++ + ++ ;
const r4 ++ + ++;
=
let 10;
const rS - - + - - ;
const r - - + - - ;
const r7 - - + - - ;
const r8 - - + - - ;

JavaScript ,
rl - r8, .
,

, .
=
let 2;
const r l ++ + ++ ;
=

11 ( (++) + (++) )
11 ( 2 + (++) ) ;
11 3
11 2 + 3 ) 4
11 5 5 ; 4
const r2 = ++ + ++;
// ( (++) + (++) )
11 ( 5 + (++) ) ;
11 5
11 ( 5 + 6 ) 6
11 11 1 1 ; 6
const r = ++ + ++;
11 ( (++) + (++) )
11 ( + (++) ) ;
11 7
11 6 + 8 8
11 14 1 4 ; 8
11
// . . .

1 09

, ,
, , -
JavaScript.
, ,
JavaScript .
, ,
.
, - (
, ).
8 + 2 + 3 (4 2 - 1)

- 25, . ,
, ,
.
, (
), JavaScript .
, JavaScript
, ,
"PEMDAS" "Please Excuse Dear Aunt Sally" (,
).
JavaScript ,
: . -
, , :
,
, .
JavaScript 56 , 19
(precedence level).
.
( ),
, ,
.
.
,
. , ( 14)
, ( -
3) . ,
.

1 10 5 .
let = 3 , ;
+= = 6 * 5 / 2 ;
11
11 :
11
11 ( - 1 4 , ) :
11 += ( 6*5) /2
11 += = (30/2)
11 += = 1 5
11 ( - 3 , ) :
11 += ( = 15)
11 += 1 5 ( 1 5 )
11 18 ( 1 8)

,
.


, ,
. : ,
( ) . (
: - " ';
.)
(strict
equality) (abstract equality).
, .
,
( ).
, ,
. ,
, === -
( ! == ). ,
.
,
( )
.
. . , ,
33 " 3 3 " , , ,
, (
). , ,
,
. ;

111
, , .
-
==, - !
=.


, favaScript: The Good Parts (
O'Reilly).


nul l, unde fined,
. , ,
, ,
.
. ,
, ,
.
, ,
;
.
,
,
,
. -
,
.


. : ,
, , , .
const n = 5 ;
const s = " 5 " ;
- --
n s; 1 1 fa lse - -
n ! == s ; 1 1 true
--- -
n Numer ( s ) ; 1 1 true - "5 " 5
n ! == Numer ( s ) ; 1 1 fa lse
--
n s; 1 1 true;
n != s; 1 1 fa lse;
const = name : " an obj ec t " } ;
cons t name : " an obj ec t " } ;
---
; 1 1 fa lse - -
! == ; 1 1 true
--
; 1 1 fa lse;
! = ; 1 1 true;

1 12 5 .

, ( 11 11
"11) ( 1). - (<),
(<=), (>) (>=).
3 > 5; 1 1 fa lse
3 >= 5 ; 1 1 fa lse
3 < 5; 1 1 true
3 <= 5 ; 1 1 true
5 > 5; 1 1 fa lse
5 >= 5 ; 1 1 true
5 < 5; 1 1 fa lse
5 <= 5 ; 1 1 true



.
, ,
NaN , (.. NaN === NaN, NaN == NaN
false). , NaN,
isNaN: isNaN ( ) t rue, NaN, false
-

.
, JavaScript - ,
( ),
.
( Nurner . MIN SAFE INTEGER Numb e r . _ SAFE
_ _ _

INTEGER ),
.
, , " "
. " "? .
JavaScript , Nurne r . EPSILON.
(2 . 2 2-1 6), ,
, . .
let n = ;
while ( t rue) {
n += 0 . 1 ;
i f ( n === 0 . 3 ) bre a k ;

console . log ( ' Stopped at $ { n } ' ) ;

, :
. 3,

1 13
. , . 1 - ,
,
.
n . 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 , fals e
.
, Numbe r . E P S I LON
, " "
.
let n = ;
while ( t rue )
n += 0 . 1 ;
i f ( Math . ab s ( n - 0 . 3 ) < Numer . E P S I LON ) bre a k ;

conso le . log ( ' Stopped a t $ { n ) ' ) ;

, ( . 3)
(n) ( Math . abs,
1 6), .
, n . 3.
,
, ,
.


JavaScript + ,
( ; ,
+ , Perl ).
, , JavaScript
. ,
. JavaScript ,
, .
, .
.
3 + 5 + 11 8 11 / / - " 8 8 11
"" + 5 + 8 11 - "358 "

JavaScript ( 3 + 5 ) ,
( 8 + " 8 " ) . ( " 3 " + 5 )
, ( " 3 5 " + 8 ) - .

114 5 .
r
, ,
, ,
( ,
),
, : .
( )

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


"" ""; ,
, : - ,
- . JavaScript ,
, .
JavaScript ( false).
undef ined
nul l
false

NaN
' ' ( )

- ( t rue ) .
, , , .
( , valueOf ( ) false).
( ).
, (, " ").
" false".
, " fa l s e " ()
( t rue ) , .
, - t rue. , arr
false, , arr . l ength ( , ,
, false ) .

AN D, OR NOT
JavaScript : AND ( & &), OR ( 1 1 ) NOT ( ! ) .
, , AND ( ) -
, OR () - NOT () - .
, ,
,
,
(. . 5.2-5.4).
n 5.2. n n AND (&&)
&&
false false false
false t rue false
t rue false false
t rue t rue true
n 5.3. n OR ( 1 1 )
x 11 v
false false false
false t rue true
t rue false t rue
t rue t rue t rue
5.4. n NOT ( ! )
!
false t rue
t rue false

, AND
t rue, - t rue; OR
false, - false. NOT ,
.
OR OR ("inclsive OR''), ,
t rue, - t rue. OR ("exclusive
OR") XOR, false, - t rue. JavaScript
XOR, XOR, .

116 5 .
OR (XOR)
, ,
( 1 1 ) & & ! == .


AND (. . 5.2),
, : - ,
. , 1 1 - ,
. JavaScript
(short-circuit evaluation).
? ,
(side effect),
. " "
- , :
, .
,
, .
, .
const skipit t rue ;
let = ;
const result s kipit 1 1 + + ;

,
result. t rue,
( s kipit ) - t rue. , , , -
, .
skipit false,
: - .
.
const do i t = fals e ;
let = ;
const result = do i t & & ++ ;

JavaScript ,
, AND false. , resul t
fal s e, . , doit t rue?
JavaScript ; ,
resul t . ? resul t ,
false? .

AND, OR NOT 117


r n r
,
.
, . 5.5 5.6.
5.5.
AND ( & & }
&&
()
()
()
()

5.6.
OR ( 1 1 }
x 11 v
()
()
()
()

, ,
AND OR.

. .
const options = supp l iedOptions 1 1 { name : " De faul t "

, ( )
. , s uppl i edOp t i on s , o p t i o n s
-

s upp l i edOpt i o n s . ,
suppliedOpt ions nul l unde fined, opt ions
.
NOT ,
, ( ! )
. , false,
-true.


- (ternary)
JavaScript: (

118 S .
). - , i f . . . else.
.
const doi t = fal s e ;
const result = do l t ? " ! " : " ! " ;

( ,
doit) , (
-

), , (
).
i f . . else, ,
.

, :
(, result ).

'1 "
"" :
. ,
, ,
, .
.
let = , = 1 0 , z ;
z = ( + + , ++ ) ;

, ,
z 1 ( ++). ,

,
. z (
+ + ), .
for (. 4)
(. 6).


, ( ) ,
( ) . ,
- " " ,
.

1 19
, 1,
, , , ,
(
, ).
32-
, .
JavaScript - , JavaScript 32-
, ,
, .
, ,
(, , , XOR), .
. 5.7 , ,

.
5 .7.

& AND l & l 1 1 :

OR 1 0 l 1 1 : 1 1 0

XOR 0 1 0 l 1 1 : 01 1 0
NOT - 1 0 1 1 : 0 1 0 1
<< 1 0 1 1 1 : 1 00
1 0 2 1 1 : l
>> (. )
>>> - (. )

, ,
.
.
1 , , , -

. , , -22.
, 22,
( .. ),
, .
let n = 22 / / 32- :
11 000000000000000000000000000 1 0 1 1 0
n >> 1 // 000000000000000000000000000 0 1 0 1 1
n >>> 1 // 00000000000000000000000000001 0 1 1
n = -n / / : 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 01 001

1 , ,

, . -
. .

1 20 5 .
n++ 11 . : 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 01 01 0
n >> 1 11 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 01 01
n >>> 1 11 01 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 01 01


, ,
( "
").
- "" (
).
, , Unix:
(read), (write) (execute).
, .
, .
const FLAG READ 1 / / ObOOl
const FLAG WRITE 2 / / 01 0
const FLAG EXECUTE 4 / /

,
, .
let = FLAG_READ 1 FLAG WRITE ; 1 1 ObO l l
let hasWrite = & FLAG_WRITE ; 1 1 01 0 -
let hasExecute = & FLAG EXECUTE ; 1 1 -
FLAG_WRITE ; 1 1 ObOOl -- wri t e
1 1 ( )
FLAG WRITE ; 1 1 ObOl l wri te
--

1 1 ( )

11
11 :
const hasRead.AndExecute = & ( FLAG_READ 1 FLAG_EXECUTE ) ;

, hasReadAndExecute
; AND , OR,
OR AND.

typeof
typeof , .
,
JavaScript (undefined, nul l, , , , ),
.
t yp e o f ,
: t ypeof nul l " ob j ect " . , null - (

121
). ,
,
.
.
typeof ,
, , .
( ), typeof
[ ] 11 obj ect 11
typeof . 5.8.
5.8. typeof

Typeof undef ined 11 undef ined 11
Typeof null 11 obj ect 11 ,
Typeof {} 11 obj ect 11
Typeof t rue 11 boolean 11
Typeof 1 11 nurner 11
Typeof 11 11 11 string 11
Typeof Sym ol ( ) 11 sym ol 11 S
Typeof funct ion ( ) {} " funct ion 11

typeof - , .
, ,
typeof typeof ( ) . -
- .

void
void : ,
undefined. ? , .
, undefined,
.
, , ,
URL HTML <>,
.
< href= " j ava script : void " > ! </>

, .


: . ,
( [- (lvalue)),

1 22 5 .
, . , ,
(
, ).
,
, , ( -
).
.
let v , v O ;
v = v O = 9 . 8 ; / / ; vO
11 9 . 8 , v 9 . 8

const nums = [ 3 , 5 , 1 5 , 7 , 5 ] ;
let n , i=O;
1 1 whi l e ;
1 1 n ums [ i ] ,
1 1 :
whi l e ( (n = nums [ i ] ) < 1 0 , i++ < nums . lengt h )
console . log ( ' co 1 0 : $ { n } . ) ;
'

console . log ( ' Haeo 1 0 : $ { n } . ' ) ;


console . log ( ' $ { nums . lengt h } . ' ) ;

,
,
.
,
, .
,
. . 5.9.
5.9.

+= = +
-
=
*= = *
/= = /
%= = %
<<= = <<
>> = = >>
>>>= = >>>
&= = &
1= = 1
"= =

1 23

S ( destructuring
assignment), ""
. .
11
const obj = { : 2 , : 3 , d : 4 } ;

/ /
const { , , } = obj ;
; 1 1 undefined: obj " "
; // 2
; 11 3
d; / / Wi : d
" "


(
).
, undefined. ,
d, .

.
, ;
JavaScript .
const obj = { : 2, : 3, d: 4 } ;
let , , ;

/ / :
{ , , } = obj ;

1 1 :
( { , , } = obj ) ;


.
11
const arr = [ 1 , 2 , 3 ] ;

/ /
let [ , ] = a r r ;
; 11 1
; 11 2
z; 11 : z Wia

, -
; , , .

1 24 5 .
(spread operator) ( . . . ),
6.
= [ 1 , 2, 3, 4, 5 ] ;
const arr
let [ , , . . . rest ] arr;
; // 1
; // 2
res t ; / / [3, 4 , 5 1

,
rest ( rest;
-

).
( ).
=
let 5, =10;
=
[ , ] [, ] ;
; 11 10
; 11 5

,
( 9).


, . ,
,
. 6.


, .
(,
), 6, 8 9.
. 5 . 1 0.
5.1 .

3
[] 3
in 9
new 9
instanceof 9
8
delete 3

1 25

(template string), 3,
.
3 .

, ? .
const roomTempC 21 . 5 ;
=

let currentTempC 19 .5;


=

cons t message = ' ' +


' $ { currentTempC-roomTempC } \u 0 0bOC . ' ;
const fahrenhei t =
' $ { currentTempC * 9 / 5 + 3 2 } \ u O O b O F ' ;

, .
, -
.


4 .
, , (
),
.

if .
else
, i f . else (
. .

,
), .
. ,
i f ( is Prime ( n ) ) {
label ' prime ' ;
else {
label ' non-prime ' ;

.
label = i s Prime ( n ) ? ' prime ' ' non-prime ' ;

1 26 5 .
if

, i f . e l se
. .

, i f
.
, if . . . e lse,
, . ,
i f ( ! opt ions ) opt ions = {};


opt ions = opt ions 1 1 {};


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

(function) - ,
; , . -
JavaScript.
.
(body) -
.
function sayHello ( ) {
/ / ; . . .

console . log ( "Hello world ! " ) ;


console . log ( " ! Hola mundo ! " ) ;
console . log ( "Hallo wereld ! " ) ;
console . log ( "pe ! " ) ;

/ / . . .

s ayHel lo.
: ,
"He l l o world ! " .
( )
, :
sayHello ( ) ; / / "Hell o, Worl d ! "

(call), (t) (r) ,


, .
,
.

- , ,
. ? (return value).
return
, .
: .
funct i on getGree ting ( ) {
r e turn " He l l o world l " ;

, , .
getGre e t ing ( ) ; / / "He l l o , Worl d ! "

return undefined.
;
getGreetings, , "Hello, World"
.


JavaScript
. ( calling)
(referencing) .
, JavaScript , :
.
, , .
JavaScript.
getGreeting ( ) ; 1 1 "He l l o , Worl d ! "
getGreeting; / / getGree ting ()

, (
), . ,
, .
const f = getGreeting;
f() ; 1 1 "He l l o , World ! "

.
const = {};
o . f = getGreet i n g ;
. f ( ) ; / / "Hello, Wor ld ! "

1 30 .
const arr = [ 1 , 2 , 3 ] ;
arr [ l ] = getGreeting; // arr [ 1 , fun c t i on getGreeting () , 2 ]
arr [ l ] ( ) ; / / "He l l o , World! "

: JavaScript
.r , ,
. arr [ 1 ] ,
. , ,
JavaScript , - .

,
, . , " whoop s " ( )
TypeErro r : "whoops " i s not
funct ion.


, .

- (argument) (
(parameter)). , ,
. ,
.
funct ion avg ( a , ) {
r e t urn ( + ) / 2 ;

(formal
-

argument).
(actual argument).
avg ( 5 , 1 0 ) ; 11 7 . 5

5 1
( ,
).
,
, ,
. .
const = 5, = 1 0 ;
avg ( , ) ;

,
avg, .

1 31
, , ,
. .
funct ion f ( ) {
sl . lg ( ' f : =$ { } ' ) ;
= 5;
console . log ( ' Byp f : =$ { } ( ) ' ) ;

let = ;
console . log ( ' epe f : = $ { } ' ) ;
f () ;
console . log ( ' oce f : = $ { } ' ) ;

,
f : =
f : =
f : x=S ( )
f : =

,
; , ,
.
, ,
.
(object type) , ,
.
funct io f ( ) {
o . me s sage = ' f ( : 1 $ { 0 . me ssage } ' ) ' ;

let = {
mes s age : " "
};
console . log ( ' epe f : o . me s s age=" $ { o . me ssage } " ' ) ;
f () ;
console . log ( ' oce f : o . me s sage= " $ { o . me s s a ge } " ' ) ;

.
f : . m s s g = " "
f : . m s sg = " f ( :
' ' ) "

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

1 32 6 .
: ,
.
.
function f ( o )
o . me s sage = " f " ;
=
mes sage : " ! "
};
cons o l e . log ( ' Byp f : o . me s s age=" $ { o . me s sage } " ( ) ' ) ;
}
let = {
me s sage : ' '
};
console . log ( ' epe f : o . me s sage=" $ { o . me s s a ge } " ' ) ;
f () ;
console . log ( ' oce f : o . me s s age= " $ { o . me ssage } " ' ) ;

,
f : . m s sg=" "
f : o . me s sage = " Ho ! " ( )
f : o . me s sage=" f "

, (
) - . f
, f,
, ,
.

JavaScript (value type),


,
.
(reference type),
(..
).

?
(signature) .
, f ( ) ( ) f ( ) (
), f ( , ) (
). JavaScript ,
f, ,
( ).

1 33
,
. ,
undefined.
function f ( ) {
return ' f : =$ { } ' ;

f ( ) ; / / " f: x=undefined"

, ,
, .


(. 5),
(destructured argument) .
, !
.
function getSentence ( { sub j e c t , verb, obj ect } )
return ' $ { subj ect } $ { verb } $ { ob j e ct } ' ;

const = {
sub j ect : " I " ,
verb : " love " ,
obj ect : " JavaScript " ,
};

getSent ence ( o ) ; 1 1 "I love JavaScript "

,
, ,
, unde fined.
.
function getSentence ( [ subj ect , verb , obj ect ] ) {
return ' $ { subj ect } $ { verb } $ { ob j e ct } ' ;

const arr = [ " I " , " love " , " JavaScript " ] ;
getSentence ( arr) ; / / "I love JavaScript "

( . . . )
.
function addPrefix (prefix, . . . word s )
1 1 !

1 34 6.
const prefixedWords = [ ] ;
for ( le t i=O ; i<words . length; i + + ) (
prefixedWords [ i ] = prefix + words [ i ] ;

return prefixedWords ;

addPre fix ( " con" , "vers e " , " vex" ) ; // [ "converse " , "convex "]

:
, .
, JavaScript ,
, .

ESS
a rguments,
.
, " " ,
.
S

a rguments ( ).


S
(default value) . , ,
undefined.
, .
function f ( , = " defaul t " , = 3 ) {
re turn ' $ { ) - $ { } - $ { } ' ;

f (S, 6, 7 ) ; 11 "5 - - 7"


f (S , 6) ; 11 "5 - - 3"
f (5) ; 11 "5 - defa u l t - 3 "
f() ; 11 "undefined - defa ul t - 3 "


,
(method), (
). 3,

1 35
.
.
const =
name : ' Wallace ' , / /
bark : function ( ) { return ' Woof ! ' ; } , / / ()

S .
.
const = {
name : ' Wallace ' , / /
bark ( ) { return ' Woof ! ' ; } , / / ()

thi s

t h i s . -
, 9.
JavaScript, , .
this ,
. this
, .
const = {
name : ' Wallace ' ,
speak ( ) { return ' $ { this . name } ! ' ; } ,

. speak ( ) , this .
. speak ( ) ; / / " Wa l l a ce ! "

, this , ,
. , this , speak -
, , ( . speak).

, , .
const spe a k o . speak ;
=

speak === o . spe a k ; / / true;


speak ( ) ; / / " ! "

JavaScript ,
; , this
undefined.

1 36 6.
,
this ( speak ),
.
, , ,
.
, .
, Code formatting ( )
MDN.

(method) -
,
,
(, . speak ( ) ).
thi s ,
, .
this ,
.
, .
const = {
name : ' Ju l i e ' ,
greetBackwards : funct ion ( ) {
funct ion getReverseName ( )
l e t nameBackwards = ' ' ;
for ( le t i=thi s . name . length- 1 ; i >= O ; i - - ) {
nameBackwards += thi s . name ( i ] ;

return nameBackwards ;

return ' $ { getReverseName ( ) } si eman ym , ol l eH ' ;


},
};
o . greetBa ckwards ( ) ;

, getReverseName,
. , getReve rs eName ,
: . greetBackwards ( ) JavaScript this,
. getReverseName
greetBackwards, this - r1
,
thi s .

1 unde f ined, ,
. ,
.

this 1 37
const = {
name : ' Ju l i e ' ,
greetBackwards : funct ion ( ) {
const s e l f = thi s ;
funct ion getReverseName ( )
l e t nameBackwards = ' ' ;
for ( le t i=se l f . name . length- 1 ; i>= O ; i - - ) {
nameBackwards += sel f . name [ i ] ;

return nameBackwards ;

return ' $ { getRever s eName ( ) } s i eman ym , olleH ' ;


},
};
o . greetBackwards ( ) ;

,
this s e l f, that. ,
,
.


(function
declaration), (.. ,
), ( ).
JavaScript (anonymous function),
.
" ,
? ?"
(function expression). ,
- , , ,
- , JavaScript.
- , (, )
. - (
) 2
,
, .
,
( ).

2 (Immediately Invoked Function Expression -


IIFE), 7.

1 38 6 .
const f = function ( )
11 . . .
};

, :
f, .
, , f ( ) .
, (
) .
:
.
.
,
. . . ,
( ) ? .
const g = function f ( ) {
11 . . .

, g ,
( ) g; f
.
? ,
( (recursion)).
const g = funct ion f ( stop) {
i f ( stop) console . log ( ' f ' ) ;
f ( true ) ;
};
g ( fa l se ) ;

f, ,
g. ,
,
.

, JavaScript (
- )? r - :
, , , .
,
. ,
, , , , ,
-
, .

1 39

S
(arrow notation). (
, ),
funct ion,
, .
.
function.
, .
- ,
return.

.
, ,
function.
.
const f 1 function ( ) { r eturn "hello ! " ; }
1 1
const f l ( ) => "hello ! " ;

cons t f2 funct ion ( name ) { r eturn ' He l l o , $ { name } ! ' ; }


1 1
const f2 name => ' He l l o , $ { name } ! ' ;

cons t f function ( , ) { return + ; }


1 1
const f ( , ) => + ;

; ,
, .
,
8.

: this , ,
. greetBackwards .
this .
const = {
name : ' Ju l i e ' ,
greetBackwards : funct ion ( ) {
const getRever seName = ( ) =>
l e t nameBackwards = ' ' ,.

1 40 6.
for ( let i=this . name . length - 1 ; i>= O ; i - - ) {
nameBackwards += this . name [ i ] ;

return nameBackwards ;
};
return ' $ { getReverseName ( ) } s i eman ym , ol l eH ' ;
},
};
o . greetBackwards ( ) ;


: (. 9)
arguments (
).

call, apply ind


, this
( - ). JavaScript
, this, ,
. call,
. this.
const bruce { name : " Bruce" } ;
=

const madel ine = { name : "Made l in e " } ;

1 1 ,
1 1 ' this ' !
funct ion greet ( ) {
return ' ! $ { th i s . name } ! ' ;

greet ( ) ; / / " ! ! " - ' this '


greet . ca l l ( bruce ) ; // " !
Bruce ! " - ' this ' 'bruce '
greet . call (made l ine ) ; / / " ! Madeline ! " - ' this '
/ / 'made l in e '

, c a l l ,
, , thi s.
c a l l , this,
-

.
function update ( birthYear, occupat ion )
t hi s . birthYear b irthYe a r ;
=

t hi s . occupat ion occupat i o n ;


=

call, apply ind 1 41


update . ca l l ( bruce, 1 9 4 9 , ' s inger ' ) ;
/ / bruce { : "Bruce " , irthYea r : 1 94 9 ,
// occupa t io : "siger " }
update . ca l l (made l i n e , 1 9 4 2 , ' actress ' ) ;
/ / adelie { : "Madeli e " , irth Year : 1 942,
// occupa t io : "actress " }

apply call, ,
. call ,
, . apply .
update . app l y ( bruce , ( 1 9 5 5 , " actor" ] ) ;
/ / bruce { : "Bruce " , irthYea r : 1 955,
// tio : "a ctor" J
update . appl y ( made l ine , ( 1 9 1 8 , "writer " ] ) ;
/ / adelie { : "Ma deli e " , irth Year : 1 9 1 8 ,
11 occupa tio : "wri ter " }

apply ,
. -
. th . rnin th .
,
, . apply,
.
const arr = ( 2 , 3 , - 5 , 1 5 , 7 ] ;
Math . mi n . appl y ( nul l , arr ) ; 11 -5
Math . max . appl y ( nul l , arr ) ; 11 1 5

, this nul l.
, Math . rnin Math . rnax
this ; ,
this.
( . . . ) S ,
apply. update, this
, call, Math .
rnin Math . rnax, ,
, .
const newBruce = [ 1 9 4 0 , "mart i a l artist " ] ;
update . c a l l ( bruce, . . . newBruc e ) ; / / apply (bruce, ewBruce)
Math . min ( . . . arr ) ; // -5
Math . max ( . . . arr ) ; // 1 5

, ind,
thi s . i nd
t h i s . , upda te

1 42 6 .
, this
bruce, , ( call, app ly
bind). bind .
const updateBruce = update . bind ( bruce ) ;

updateBruce ( l 9 0 4 , " actor " ) ;


11 bruce ( : "Bruce " , birthYear : 1 90 4 , occupa tio : "a ctor" }
updateBruce . ca l l (madeline, 1 2 7 4 , " king" ) ;
1 1 bruce ( : "Bruce " , irthYear : 1 2 7 4 , occupa tio : "king" } ;
11 adeline wro !

, bind ,
, :
, call, app l y
bind ( ). , ,
, call apply
, this. , ind
, , .
ind ,
, .
, update,
bruce 1 9 4 9, ,
.
const updateBruce l 9 4 9 = update . bind ( bruc e , 1 9 4 9 ) ;
updateBruce l 9 4 9 ( " s inger, songwriter " ) ;
1 1 bruce ( : "Bruce " , irth Year : 1 94 9 ,
11 occupa t ion : "singer, songwriter" }


- JavaScript. ,
:
. -
, . ,
.
7

(scope) , ,
.
: , .
.
function f () {
return + 3 ;

f (5) ; 11 8
; 1 1 Referen ceError :

, (
+ 3 ), . ,
, - f.
, - ,
, ,
( , ,
). ,
, .
,
, . , ,
let cons t (var -
, ).


(declaration) (definition). ,
, ,
. , ,
. JavaScript
,
(
undefined).

, ,
. , , ,
, ,
.
? , ,
? ,
(scope) (existence) .
( (visiility)) ,

( (execution context)).
, , , ,
(.. ) .
, , .
, JavaScript
:
(garbage collection).
JavaScript
.


, (lexical
structure). ,
. .
funct ion fl ( ) {
console . log ( ' one ' ) ;

funct ion f2 ( ) {
console . log ( ' two ' ) ;

f2 ( ) ;
f1 ( ) ;
f2 ( ) ;

- ,
. ,
f2, - fl ( ,
f2) - f2.

1 46 7.
JavaScript , ,
, ,
. ,
: ,
.
,
,
( ). .
const 3;
=

function f ( ) {
console . log ( x ) ; / /
console . log ( y ) ; / / -

const 3;
f() ;

f ,
- . f.
f , .
-

: f ,
, L.
JavaScript (global scope),
(k scope) (function scope).


, .
, ,
(global scope). JavaScript
(, )
. , , ,
.
, ,
, , , .
,
" ".
?
, . ,
. ,
.
: .

1 47
: ",
!"
, .
, , ,
... !
: , ,
, , ,
. :
.
, , .
, .
let n ame = " I rena " ; / /
let age = 2 5 ; / /

funct ion greet ( )


console . log ( ' He l l o , $ ( name } ! ' ) ;

funct ion getBirthYear ( )


return new Date ( ) . ge t Ful lYear ( ) - age ;

,
( ), . (
) name ( ).
"name " " age" ( )
. greet
getBi rthYear , , ,
, name age .
.
let user = (
name " I rena " ,
=

a ge = 2 5 ,
};

funct i on greet ( ) (
console . log ( ' He l l o , $ ( user . name } ! ' ) ;

funct ion getBirthYea r ( )


return new Date ( ) . getFullYear ( ) - user . age ;


( name age,
user), 10 ... 1 00?

148 7.
: greet getB i r thYear
user, - .
,
.
function greet ( us e r )
console . log ( ' Hello, $ { user . name } ! ' ) ;

funct ion getBirthYear ( u s e r ) {


return new Date ( ) . getFul lYea r ( ) - user . age ;

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


l e t const
(lock scope). 5 , - ,
. ,
, .
console . log ( ' epe ' ) ;
{
console . log ( ' yp ' ) ;
const = 3 ;
console . log ( x ) : / /

console . log ( ' a ; =$ { } ' ) ; // ReferenceError :

(standalone k):
, i f for, ,
. ,
.
4 ,
; -
( ), .
,
.

1 49


.
, .

1 1 1
const = ' u ' ;
conso l e . log ( ) ; / / " "

console . lo g ( typeof ) ; 1 1 "undefined";


{
1 1 2
con s t = 3 ;
console . log ( x ) ; 1 1 ,,3,,

console . lo g ( typeof ) ; / / "undefined " ;

, , ,
. ,
.

//
let = ' u ' ;
console . log ( x ) ; 1 1 " "
{
1 1
let = 3 ;
console . log ( x ) ; / / "3 "

console . log ( ) ; / / " "

console . log ( typeof ) ; 1 1 "undefined";

(variale masking).
(
), ( ), ,
.
, ,
,
;
( ).
, , ,
.

1 50 7.
.

1 1
l e t = { color : "u" } ;
let ; 1 1
let z = 3 ;
{
1 1
let = 5 ; 1 1
console . log ( x ) ; 1 1 5
console . log ( y . color ) ; 1 1 " u " ; ,
1 1 (
1 1 ) ,
1 1
y . color = " red" ;
console . log ( z ) ; 1 1 3; z

console . log ( x . color ) ; 11 "red" ;


11
console . log ( y . color ) ; 11 "red";
11
console . log ( z ) ; 1 1 3

(shadowing)
( ..
).
, -
, .
, .


: , .
, ,
:
( ) .

,

,
,
. , , ,

, 1 51
- , , ,
, .
""
,
( ),
, .
JavaScript, ,
, . ,
, , ,
.

, .
(closure) (
, ).
.
l e t globa l Fun c ; / /

let lockVar = ' ' ; 1 1


global Func = funct ion ( )
console . log ( l ockVar ) ;

globalFunc ( ) ; / / " "

glob a l Func :
( , )
. , globalFunc,
.
: global Func
ockVar, 1
.
.
JavaScript , (
),
.
,
;
,
. .
let f; / /

let = { not e : ' ' } ;

1 52 7.
f fuct i o ( )
retur ;

l e t oRef = f ( ) ;
oRe f . o t e = " ! " ;

.
, ,
. .



6 .

(Immediately Invoked Function Expression - IIFE). IIFE ,
. ,
, , . IIFE
.
( fuct io ( ) {
/ / IIFE
} ) () ;

, ,
. IIFE ,
, , ,
.
cost message = ( func t i o n ( )
con s t secret = " ! " ;
return ' $ { s e cret . lengt h } . ' ;
}) ();
consol e . l og ( me s s age ) ;

secret IIFE,
. IIFE , ,
, . ,
.
const f = ( function ( )
let count = ;
return function ( )
return ' $ { ++count } ( ) . ' ;

1 53
}) () ;
f ( ) ; / / " () . "
f ( ) ; / / " 2 ( ) . "
11" .

count IIFE,
: f ,
.
S
IIFE, ,
.



S let
var (function scope) (
, var ,
).
let,
.
var, ".
. , ,
, , ,
undefined. ,
, , unde fined, - .
l e t var l ;
let var2 unde f ined;
varl ; / / undefined
var 2 ; / / undefined
undefinedVar ; / / Referen ceError : undefin edVar

let ,
.
; / / Referen ceError :
l e t = 3 ; / / -

, var, ,
, .
; / / undefined
var = 3 ;
; // 3

1 54 7 .
? ,
. ,
var, (hoisting). JavaScript
( )
, var. ,
, . , JavaScript
.
var ; / / ( )
; / / undefined
= 3;
; 11 3
,
JavaScript .
/ / / / JavaScript
var ;
var ;
i f ( x ! == 3 ) { i f ( x ! == 3 ) {
console . log ( y ) ; console . log ( y ) ;
var = 5 ; = 5;
i f ( y === 5 ) { if (y === 5)
var = 3 ; = 3;

console . log ( y ) ; console . log ( ) ;

i f ( === 3 ) { i f ( === 3 ) {
console . lo g ( y ) ; console . lo g ( y) ;

, JavaScript.
, .
. ,
.
, var, -
JavaScript .
/ / / / JavaScript
var ;
var = 3 ; = 3;
i f ( === 3 ) i f ( === 3 ) {
var = 2 ; = 2;
console . log ( x ) ; console . log ( x ) ;

conso l e . log ( x ) ; console . log ( x ) ;

, (
) var

155
. ,
let.
, var.
, .
( )
,
, i f,
.
" var
?': ,
let. , var
, ,
. S
"" var,
; let.
var,
let .
, var let,
JavaScript ( ) ,
let var ( ,
var ).
, var ?
. -, S
, , ESS, , ,
, ESS.
, var. -,
, .


var,
.
, .
f() ; 1 1 "["
functi on f ( ) {
consol e . log ( ' f ' ) ;

, ,
, .
, .

1 56 7 .
f() ; 1 1 TypeError : f -
let f = function ( ) {
console . log ( ' f ' ) ;


(Temporal Dead Zone - TDZ) -
, ,
let, .
,
.
,
TDZ, , JavaScript S.
t ypeof , ,
"" . ,
let TDZ,
.
if ( typeof "'== " undefined " ) {
console . log ( " x unde fined " ) ;
else {
1 1 . . . .

l e t
. , .
if ( t ypeof "'== "unde fined " ) {
console . log ( " x unde fined " ) ;
else {
/ ! . . . .

let = 5;

typeof S
, typeof
.


ESS (implicit global),
. ,
var, JavaScript
, .

1 57
, !
, .
( ) JavaScript
(strict mode), .
"use strict" (
),
, . ,
, ,
.
,
, .
- ,
.
. , ,
, ,
. ,
.
( ?),
( 1 3).
( function ( ) {
' use s t r i ct ' ;

// . . . ,
// ,
//
// ,
11
}) ();

, .
( !),
, !
,
MDN.


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

1 58 7 .
8

- JavaScript.
,
JavaScript
.
JavaScript.


, . (
) ,
. JavaScript , ..
( ,
r ).
,
. length,
. ,
, ,
unde f ined.
Array, . ,
, .
/ /
const arrl [ 1 , 2, 3 ] ; //
const arr2 [ " one " , 2, " three " ] ; / /
const arr3 [ [ 1, 2, 3] , [ "one " , 2 , " thre e " ] ] ; / / ,
1 1
const arr4 / /
{ name : " Fred " , type : " ob j ect " , luckyNumers = [ 5 , 7 , 1 3 ] } ,
[
name : " Susan " , t ype : " ob j ect " } ,
name : "Anthony" , t ype : " ob j e ct " } ,
]'
1,
funct ion ( ) { return " " ;
},
" three " ,
];

/ /
arrl [ O ] ; 11 1
arr1 [ 2 ] ; 11 3
arr [ l ] ; 11 [ " " , 2 , "three "]
arr4 [ 1 ] [ ] ; // { : "Susan " , type : "obj ect " }

/ /
arr l . l ength ; 11 3
arr4 . lengt h ; 11 5
arr4 [ 1 ] . length ; 11 2

/ /
arr 1 [ 4 ] = 5 ;
arr l ; / / [ 1 , 2 , 3 , undefined, 5 ]
arrl . lengt h ; 11 5

/ / ( ) , ,
/ / , **
arr2 [ 1 0 ] ; / / undefined
arr2 . lengt h ; 11 3

/ / Array ( )
const arrS new Array ( ) ; 1 1
const arr new Array ( l , 2 , 3 ) ; 1 1 [ 1 , 2 , 3 ]
const arr7 new Array ( 2 ) ; 1 1 2 (
1 1 undefined)
con s t arr8 new Array ( " 2 " ) ; 1 1 [ "2 "]


,
. , , ,
, " '',
, . ,
, (,
push , concat - ).

, Ruby, ,
,
. , Ruby, str
s t r . downcase,

1 60 8.
, s t r . ,
s t r . downcase ! , s t r .
, JavaScript
, ,
, ,
, .



, (
). (
arr . length-1 arr) . push
( ) . shi ft unshift
( ) .

.
(push) () - (stack),
, .
shift unshift (queue), -
, .

push unshift
, shift .
.
const arr = [ " " , " " , " d" ] ;
arr . push ( " e " ) ; 1 1 4 ; a rr [ " " ," " , "d " , " "]
arr . ( ) ; 11 ""; arr [ " " , "", "d"J
arr . unshi ft ( " a " ) ; 1 1 4 ; arr [ " ", " " , " " , "d "J
arr . shift ( ) ; 11 " "; arr [ " " , "", "d "]


concat .
concat ,
. .
const arr = ( 1 , 2 , 3 ] ;
arr . concat ( 4 , 5 , 6 ) ; 1 1 [1 , 2, 3 , 4 , 5 , 6] ; a rr
arr . concat ( [ 4 , 5 , 6 ] ) ; 1 1 [1 , 2 , 3 , 4 , 5 , 6) ; arr
arr . concat ( [ 4 , 5 ] 1 6) ; 1 1 [1 , 2 , 3 , 4 , 5 , 6) ; arr
arr . concat ( [ 4 , [ 5 , 6 ] ] ) ; 1 1 [1 , 2 , 3, 4 , [ 5 , 6] ] ; a rr

161
, concat ,
; .


, s l ice,
. - ,
- ( ).
, .

, . .
const arr = [1, 2, 3, 4, 5] ;
arr . sl i c e ( 3 ) ; 11 [ 4 , 5] ; arr
arr . s l i ce ( 2 , 4 ) ; 11 [3, 4 1 ; arr
arr . s l i ce ( -2 ) ; 11 [ 4 , 5] ; arr
arr . s l i ce ( l , -2 ) ; 11 [2, 3] ; a rr
arr . s l i ce ( - 2 , - 1 ) ; 11 [ 4 1 ; arr


s p l i c e , /
. - ,
; - (
, ), -
. .
const arr = [ 1 5 , 7 ] ;
/

arr . splice ( l , , 2 , 3 , 4 ) ; 11 [ ] ; arr [ 1 , 2, 3, 4 , 5, 7)


arr . splice ( 5 , , 6 ) ; 11 [ } ; a rr [ 1 , 2, 3, 4, 5, 6, 7]
arr . splice ( l , 2 ) ; 11 [2, 3] ; a rr [ 1 , 4 , 5, 6, 7]
arr . splice ( 2 , 1 , , 1 ,
'' ) ; 11 [ 5 ] ; arr [ 1 , 4, ' ' , ' ' , 6, 7]


S , copyWi thin,
, ,
, . -
, - , ()
- . s l ice,
;
. .
const arr = [ 1 , 2 , 3 , 4 ] ;
arr . copyWithin ( l , 2 ) ; / / arr [1 , 3 , 4 , 4 1

1 62 8.
arr . copyWithin ( 2 , , 2 ) ; 1 1 arr [ 1 , 3, 1 , 3 }
arr . copyWithin ( O , - 3 , - 1 ) ; 1 1 a r r [3, 1 , 1 , 3 }


S , f i l l,
( ). ,
Array (
).
, (
). .
const arr = new Array ( 5 ) . fill ( l ) ; 1 1 arr [ 1 , 1 , 1 , 1 , 1 }
arr . f ill ( " a " ) ; 1 1 arr [ " " ' " " , " " ' " " ' " " }
arr . fill ( "b " , 1 ) ; 1 1 arr [ " ", " " , " " ' " " , " " }
arr . fill ( " c " , 2 , 4 ) ; 1 1 arr [ " "' " " , '' " , " " ' " " }
arr . fill ( 5 . 5 , - 4 ) ; 1 1 arr [ " "' 5 . 5 , 5 . 5 , 5 . 5, 5 . 5}
arr . fill ( O , - 3 , - 1 ) ; 1 1 arr [ " "' 5 . 5 , , , 5 . 5]


reve rse , (
).
const arr = [ 1 , 2 , 3 , 4 , 5 ] ;
arr . reverse ( ) ; 1 1 arr [5, 4 , 3 , 2 , 1 }

sort ( ).
const arr = [5, 3 , 2 , 4 , 1 ] ;

arr . sort ( ) ; 1 1 arr [ 1 , 2, 3 , 4 , 5 }

sort (sort function),


. ,
.
const arr = [ { name : " Suzanne" } , name : " Jim" } ,
{ name : " Trevor" } , name : "Amanda" } ] ;
arr . sort ( ) ; 1 1 arr
arr . s ort ( ( a , ) => a . name > b . name ) ; 1 1 arr
1 1
1 1
arr . sort ( ( a , ) => a . name [ l ] < b . name [ l ] ) ; 1 1 arr
1 1
1 1
1 1

1 63
.
sort .
, sort ,
"'', . ,
, , ,
k.
, k,
j l, k
(.. ).


- , .
indexOf, JavaScript
. indexOf ,
( lastindexOf,
,
). ,
. indexOf ( last indexOf) -1,
, .
cost = { : 11 Jerry 11 } ;
cost arr = [ 1 , 5 , 11 11 , , true , 5, [ 1 , 2 ] , 11 9 11 ] ;
arr . indexOf ( 5 ) ; 1 1 1
arr . l a s t indexOf ( 5 ) ; 1 1 5
arr . idexO f ( 11 a 11 ) ; / / 2
arr . l a s t indexOf ( 11 a 11 ) ; // 2
arr . indexOf ( { : 11 Jerry 11 } ) ; 11 -1
arr . indexOf ( o ) ; // 3
arr . indexOf ( [ 1 , 2 ] ) ; 11 -1
arr . idexO f ( 11 9 11 ) ; 11 7
arr . idexOf ( 9 ) ; 11 -1
arr . idexOf ( 11 a 11 , 5 ) ; // -1
arr . idex0f ( 5 , 5 ) ; 11 5
arr . l a s t idexOf ( 5 , 4 ) ; // 1
arr . l a s t idexOf ( true , 3 ) ; 11 -1

, f indindex indexOf ,
( - 1 ), .
, , ( f indindex
lastindexOf).
cost arr = [ { id : 5 , : 11 Judith 11 } , { i d : 7 , : 11 Francis 11 ) ] ;
arr . findindex ( o => o . id === 5 ) ; / /
a rr . findindex ( o = > . === 11 Fracis 11 ) ; / / 1

1 64 8.
arr . findindex ( o = > === 3 ) ; 1 1 -1
arr . findindex ( o = > o . id === 1 7 ) ; // -1

find findi ndex .


, ? find
findindex , ,
, ( nul l, ).
const arr = [ { i d : 5 , name : " Judit h " } , { i d : 7 , name : " Franc i s " } ] ;
arr . find ( o = > o . id 5 ) ; / / ( id: 5 , : "Judi th "
arr . find ( o > o . id === 2 ) ; / / null
=

, find findindex, ,
,
. , ,
, .
const arr = [ 1 , 1 7 , 1 6 , 5 , 4 , 1 6 , 1 0 , 3 , 4 9 ] ;
arr . find ( ( , i ) => i > 2 && Nurne r . i s i nteger ( Ma t h . sqrt ( x ) ) ) ; / / 4

find findindex this


. ,
, .
Person .
class Person {
constructor ( name )
t hi s . name = name ;
this . id = Person . next id++ ;

Person . next i d =;
const j amie new Person ( " Jamie " ) ,
j ul i e t new Person ( " Ju l ie t " ) ,
peter new Person ( " Peter" ) ,
j ay new Person ( " Jay " ) ;
const arr = [ j amie , j ul i e t , peter, j ay ] ;

/ / 1 : :
arr . find ( p = > p . id j ul i e t . id ) ;
=== / / j ul i e t

/ / 2 : "this " :
arr . find ( p = > p . id this . id , j ul i e t ) ; / / j ul i e t
===

, , thi s
find findindex, ,
.

1 65
, ,
: ,
. ,
, - 1 null, JavaScript : some
every.
some t rue, ,
( , , ) , fa l s e
. .
const arr = [ 5 , 7 , 1 2 , 1 5 , 1 7 ] ;
arr . some ( x => % 2===0 ) ; / / true; 1 2
arr . some ( x => Numer . i s integer ( Math . sqrt ( x ) ) ) ; // fal s e ;

eve ry t rue,
, false . false,
, ;
.
const arr = [ 4 , 6, 1 6 , 3 6 ] ;
arr . every ( x => % 2 === 0 ) ; // true;
arr . every ( x => Numer . i s i nteger ( Math . sqrt ( x ) ) ) ; / / fa lse; 6 -

, , s ome
every , this
.

n
: map f i l ter
map f i l t e r .
, .
map . ? .
, , ? !
, ? ! ,
, ,
map. map f i l ter .
.
const cart = [ { name : "Widget " , price : 9 . 95 } , { name : " Gadge t " , price : 2 2 . 9 5
}];
const names = cart . map ( x => x . name ) ; // [ "Widget ", "Gadget "J
const prices = cart . map ( x => x . price ) ; // [ 9 . 95 , 22 . 95 ]
const discountPrices = price s . map ( x => * . 8 ) ; // [ 7 . 96, 1 8 . 3 6}
const l cNames = name s . map ( String . toLowerCa se ) ; // [ "widge t " , "gadget "]

1 66 8.
" l cNames?
, ': , ,
map, , .
names, prices discountPrices (
). l cNames , ,
String . toLowerCase. ,
. names . map ( = >
. toLowe rCase ( ) ) , , - ,
, .
.
: , (
). ,
, .
const i tems = [ "Widge t " , " Gadget " J ;
const prices = [ 9 . 95 , 22 . 9 5 ) ;
const cart = i t ems . map ( ( x , i ) => ( { name : , price : prices [ i ] } ) ) ;
1 1 cart : [ ( : "Widge t " , price : 9 . 95 } , ( : "Gadge t " , price : 22 . 95 } ]

, map.
, (), ( i ) .
, i tems
prices . map
, . ( ,
;
.)
filte r, ,
. map,
. ? .
, ,
. .
1 1
const cards = ( ] ;
for ( le t suit of [ ' ' , ' ' , ' D ' , ' S ' ] ) 1 1 , , ,
for ( le t value=l ; value<= l ; value+ + )
cards . push ( { suit , value } ) ;

1 1 2 :
cards . fi l t e r ( c => c . value === 2 ) ; 1 1 [
1 1 ( sui t : ' ' ' val u e : 2 } '
' '
1 1 ( sui t : ' val u e : 2 } '
1 1 ( s ui t : 'D , ' val u e : 2 } '
1 1 ( sui t : , s , , val u e : 2 }

: map filter 1 67
11 ]

/ / ( )

/ / :
cards . fi l t e r ( c => c . suit 'D' ) ; 1 1 : 1 3

/ /
cards . fi l t e r ( c => c . va lue > 1 0 ) ; 1 1 : 1 2

/ /
cards . fi l t e r ( c = > c . value > 1 0 & & c . suit === ' ' ) ; / / : 3

, , map filter
. , ,
.
"\.', "J", "Q" "" .
,
.
function cardToString ( c )
const suits = { ' ' : ' \u 2 6 6 5 ' , ' ' : ' \u2 6 63 ' , ' D ' : ' \u2 6 66 ' , ' S ' : ' \u2 6 6 0 '
};
const values = { 1 : ' ' , 1 1 : ' J ' , 1 2 : ' Q ' , 1 3 : ' ' } ;
/ / cardToString
/ / ;
for ( le t i=2 ; i<=l O ; i + + ) value s [ i ) = i ;
return value s [ c . va lue ] + suits [ c . su it ] ;

/ / 2 :
cards . fi l t e r ( c = > c . va lue === 2 )
. map ( cardToString ) ; 1 1 [ 2'1 , 2 , 2+ , 2 ]

/ /
cards . fi lter ( c => c . value > 1 0 & & c . suit === ' ' )
. map ( cardToString ) ; / / [ J'I , Q'I , K'I

r : reduce
reduce. map
-

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

1 68 8.
-
reduce map f i l t e r (
, ).
reduce, map fi lter, ,
.
(callback),
. reduce - (accumulator),
. :
, .
, reduce ()
. -
.
const arr = [ 5 , 7 , 2 , 4 ] ;
const sum = arr . reduce ( ( a , ) => += , 0 ) ;

reduce : ()
().
. reduce, ,
JavaScript, , .
1 . (5) () .
, , - 5.
(5), .
2. (7).
5 ( ), 7 .
(12), .
3. (2).
12, - 2. ( 1 4 ) .
4. , , ( 4 ).
. 1 4 , - 4 .
( 1 8 ) , reduce (
sum) .

,
; ,
(, r e turn ) ,
, + .
.
, - .

: reduce 1 69

reduce, , ,
, .. unde f i ned. reduce

. ,
.
const arr [ 5 , 7, 2 , 4 ) ;
const sum arr . reduce ( ( , ) => += ) ;

1 . ( 7 ) () .
5 ( ), 7 .
( 1 2 ),
.
2. (2).
12, - 2. ( 1 4 ).
3. , , ( 4 ).
1 4, - 4 .
( 1 8 ) , reduce (
sum) .

, , .
( ,
) , .
reduce
( ), -
( ). ,

( , ..), .
const words = [ "Beachba l l " , "Rodeo" , "Ange l " ,
"Aardvar k " , "Xylophone " , "Novemer " , "Chocolate " ,
" " , "Uni form" , "Joker" , "Clover" , "Bal i " ] ;
const alphabetical = words . reduce ( ( a , ) => {
if ( ! a [x [O ] J ) a [x [ OJ J = [ ] ;
[ [ 0 ] ] . push ( ) ;
return ; } , { } ) ;

, .

; , (
" Be a chba l l " . ,
). (, ,
) , ( ) (,

1 70 8.
, ,
).
- . , ,
.
con s t data = [ 3 . 3 , 5 , 7 . 2 , 1 2 , 4 , 6 , 1 0 . 3 ] ;
11 :
11 , 2 . , 3 - . 2000
cons t stats = dat a . reduce ( ( a , ) => {
a . N++;
let de l t a =
- a . me a n ;
a . mean + = delta / a . N ;
. 2 + = del t a * ( x - a . me an ) ;
return ;
} , { N : , mean : , 2 : } ) ;
i f ( st a t s . N > 2 ) {
stats . variance = s t at s . M2 / ( st a t s . N
- l) ;
stat s . stdev = Math . s qrt ( st a t s . variance ) ;

,
( - mean 2: N
).
, reduce
, , - .
cons t words = [ "Beachbal l " , " Rodeo " , "Ange l " ,
"Aardvark" , "Xylophone" , "Novemer " , "Chocol a t e " ,
" " , " Uni form" , " Jo ke r " , " Clove r " , "Bali " ] ;
const longWords = words . reduce ( ( , w } => w . length> ? + " " +w : , " " } . trim ( } ;
11 longWords : "Bea chba l l Aardvark Xyl ophone November Chocol a t e Uniform"

,
, .
, reduce
filter j oin ( ). ( "
trim reduce?")
, reduce.
.

171
. map, filter reduce
, . ,
S, ,
.
const arr = Array ( l O ) . map ( functi on ( x ) { return 5 } ) ;

arr 1 0 ,
undefined. , ,
map, "':
cons t arr = [ 1 , 2 , 3 , 4 , 5 ] ;
del e t e arr [ 2 ] ;
arr . map ( x => ) ; // [ , , < >, , ]

,
, (
, , delete
), .


()
, . Arra . protot . j oin
, ( - , ),
(
; null unde fined
).
con s t arr = [ 1 , null , "hel l o " , "world" , true , undefine d ] ;
del e t e arr [ ] ;
arr . j oi n ( ) ; 11 "1 , , hello, , true, "
arr . j oin ( ' ' ) ; / / "lhellotrue "
arr . j oin ( ' -- ' ) ; / / "1 -- -- hello -- -- true "

(
) Array . prototype . j oin ,
HTML <ul>.
con s t attribute s = [ "Nime " , " Perceptive " , " Generous " J ;
cons t html = ' <ul><l i> ' + a t t r ibut es . j oin ( ' < / l i><l i > ' ) + ' < / l i></ul> ' ;
/ / h tml : "<ul><li>Nime</l i><li>Percep t i ve</ l i><li>Generous</ l i></ul> " ;

, :
<li>!

1 72 8.

JavaScript Array ,
, .
Array . 8. 1 -8.4.
Arra y . prot otype, ( find, findindex,
some, every, map, f i l t e r reduce ) , ,
. 8 . 1 , .
8.1 . ( )

reduce ( ,
)
( )

( )

Array . prototype, ,
this, ,
.

8.2.
". ".

(" , push ( ),
" [LIFOJ)
(" , unshift ( ),
" [FIFO]) shift
concat

s lice
spli ce

copyWithin

fill
reverse
sort ( -
)
8.3.
/". ".
indexOf ( ), findlndex (
)
lastindexOf ( )
f ind
, - s ome

- every

8.4.
". ."
map
f i lter

reduce
j oin

1 74 8.
9

JavaScript 3,
.
, JavaScript - ,
.
.
, ;
, .
( arr [ ] arr [ 1 ] );
( , obj
.

obj . ).

( ) ,
, .
(property) (key) ( ) (value).
, .


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

for . . . in
for . . . in.
,
.
const SYM Symol ( ) ;

const = : 1 , : 2, : 3, [ SYM] : 4 } ;

for ( le t prop i n ) {
i f ( ! o . hasOwnProperty (prop) ) cont inue ;
conso l e . log ( ' $ { prop } : $ { o [ prop] } ' ) ;

. . . , ,
" hasOwnPrope rty?" ,
for . . . in, .
. . ,
( , ),
, .
hasOwnProperty.
, , ,
( ) .
, for . . . in
.

for . . . i n
, .
for forEach.
-----_J
Obj ect . keys
Obj ect . keys
.
const SYM Symol ( ) ;

cons t = : 1, : 2, : 3, [ SYM] : 4 } ;

Obj e c t . keys ( o ) . forEach ( prop => console . log ( ' $ { prop } : $ { o [ prop] } ' ) ) ;

1 76 9. -
, for . . . in (
hasOwnProperty). ,
. ,
, .
const = { appl e : 1 , xochit l : 2 , balloon : 3 , guitar : 4 , xylophone : 5 , };

Obj ect . keys ( o )


. fi lter ( prop => prop . match ( / x/ ) )
. forEach ( prop => console . log ( ' $ { prop } : $ { o [ prop ] } ' ) ) ;

-
- (, Obj ect-Oriented
Programming) - . ,
, 1 950- ,
Simula 67 Smalltalk .
: -
.
. , (,
-

, , (VIN) ..),
(, , ,
..). , ()
( ).
, .
(class) (), (instance) (
(object instance)) - (
, " "). ()
(method). , ,
, (, " VIN"
:
, , ,
, VIN). ,
(constructor). .

. , .
(,
),
(, ,
, ). , -
(superclass) , - (subclass)
.
: , , , , ..

- 1 77
, , . ,

, , , , ..
,
, , .


S JavaScript
. .
class Car {
const ructor ( )
}

Car. (
) , .
, new.
cons t carl new Car ( ) ;
const car2 = new Car ( ) ;

Car. Car
, instanceof, ,
.
carl instanceof Car // true
carl instanceof Array // fa lse

, carl Car, Array .


- -

Car . (
, ) ( ).
class C a r {
constructor ( ma k e , mode l )
this . make = ma ke ;
this . model = mode l ;
this . u s e rGears = [ ' ' , ' N ' , ' R ' , ' D ' J ;
this . us erGear = thi s . us erGears [ O ] ;

shift ( ge a r ) {
i f ( this . userGears . indexOf ( ge a r ) < 0 )
throw new rrr ( ' : $ { gear } ' ) ;
thi s . u s e rGear = gear;

this :
, . :

1 78 9 . -
, , , this
,
.
, :
(userGears) (gear),
. (
(user gears) ,
, , ,
.)
( ),
shi ft, . .
const carl = new Car ( " T e s la " , "Model S " ) ;
const car2 = new Car ( "Mazda " , " i " ) ;
carl . shift ( ' D ' ) ;
car2 . shift ( ' R ' ) ;

, carl . shi ft ( ' D ' ) , this


carl. car2 . shift ( ' R ' ) car2.
, carl D (drive), car2
R (reverse).
> carl . userGear // "D "
> car2 . userGear / / "R "


, shi ft Car
, .
, ,
: carl . userGear = ' ' . -
,
,
. JavaScript , .
1 .
.
Car , .
c l a s s Car {
constructor (make , model )
thi s . ma ke = make ;
thi s . model = model ;
thi s . _userGears = [ ' ' , 'N' , 'R' , ' D' ] ;
thi s . _userGear = thi s . _us erGears [ O ] ;

1 (accessor
properties), 2 1 .

- 1 79
get userGea r ( ) { return thi s . userGea r ;
s e t userGea r ( value ) {
i f ( this . _use rGears . indexOf ( value ) < 0 )
throw new rrr ( ' : $ { value ) ' ) ;
t hi s . use rGear value ;
=

shift ( ge a r ) { thi s . us erGear = gea r ; )

, ,
_userGear : carl . _userGear =
' ' . " " - ,
, .
,
, .
,
WeakMap (. 1 0),
( WeakMap,
, ,
, ).
, Car .
const Car = ( function ( ) {

const carProps = new W e a kMap ( ) ;

c l a s s Car {
constructor ( ma ke , mode l )
thi s . ma ke = ma ke ;
t hi s . model model ;
=

thi s . _userGears = [ ' ' , ' N ' , ' R ' , ' D ' ] ;
carProps . set ( th i s , { userGea r : t hi s . userGears [ ] ) )
_ ;

get userGear ( ) { return carProps . ge t ( th i s ) . userGear ;


s e t userGear ( value ) {
i f ( this . _userGears . indexOf ( value ) < 0 )
throw new rrr ( ' : $ { value ) ' ) ;
carProps . get ( th i s ) . us erGear = value ;

shift ( ge a r ) { thi s . userGear gea r ; )

return C a r ;
}) ();

1 80 9. -
WeakMap ,
,
(. 13). Weakap ,
.
,
;
, , ,
.


S class
, . class
, JavaScript
( class
), , JavaScript.
- . ESS
Car .
funct ion Car (ma ke , mode l )
thi s . make =ma ke ;
t h i s . model mode l ;
=

t hi s . _userGears = [ ' ' , ' N ' , ' R ' , ' D ' ] ;


thi s . _userGear = thi s . userGears ( O J ;

S - (
). , .
class E s Car { } 1 1
function E s5Car { }
> typeof E s Car 1 1 "funct ion "
> t ypeof E s5Car 1 1 "fun c tion "

, S ;
.


, ,
(prototype) . , shift,
Car,
Car . prototype . shift. ( forEach Array
Arra y . prototype . forEach. )
, JavaScript ( dynamic
dispatch), (prototype chain).

- 181
( # )
. ,
Car . prototype . shift, Car # shift.

prototype. (
f, f . prototype.)
, ,
.
(
- ) , Car.
- , ,

- .
prototype ,
new:
protot .
_proto_
proto JavaScipt,
,
. , ,
. ,
JavaScript,
( ) .
( "dispatch" -

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

.
.
- ,
, , -
.
, .
,
; , JavaScript ,
- . .

1 82 9. -
1 1 Ca r shift
const carl = new Car ( ) ;
const car2 = new Car ( ) ;
carl . shift === Car . prototype . shift ; / / true
carl . s hift ( ' D ' ) ;
carl . s hift ( ' d ' ) ; 1 1
carl . userGear ; / / 'D '
carl . shift === car2 . shift 1 1 true
carl . shift = function ( ge a r ) thi s . use rGear gear . toUpperCas e ( ) ; }
carl . s hift === Car . prototype . shift ; / / fa lse
carl . shift === car2 . shift ; / / fa lse
carl . s hift ( ' d ' ) ;
carl . userGear ; / / 'D '

, JavaScript .
carl shi ft, car l . shift ( ' D ' )
JavaScript carl .
shift , carl
. carl . shift ( ' d ' ) ,
carl, .

, ,
. , , .


, ,
(instance method). .
(static method) ( (class method)),
.
this ,
.
,
, .
VIN ( ).
VIN:
VIN,
? VIN ,
; , .
,
(). ,
areS irnilar, t rue,
, areSarne, t rue,
VIN. , Car.

- 1 83
class Car {
static getNextVin ( )
return Car . nextVin + + ; / /
/ / this . nextVin+ + , Car
/ / ,

const ructor (make , model )


thi s . ma ke = make ;
thi s . model = mode l ;
thi s . vin = Car . getNextVin ( ) ;

s t a t i c areSimilar ( car l , car 2 ) {


return carl . ma ke===car2 . ma ke && car l . model===car2 . mode l ;

s t a t i c areSame ( carl , car2 ) {


return carl . vin===car2 . vi n ;

Car . nextVin = ;

const carl new Car ( " Te s la " , " S " ) ;


const car2 new Car ( "Mazda " , " 3 " ) ;
const car3 new Car ( "Ma zda " , " 3 " ) ;

car l . vin; //
car2 . vi n ; // 1
car3 . vin // 2

Car . areSimi lar ( ca r l , car2 ) ; 11 fa lse


Car . areSimil a r ( car2 , car3 ) ; 11 true
Car . areSame ( car2 , car3 ) ; 11 fa lse
Car . areSame ( car2 , car2 ) ; 11 true


, :
, .
: ,
. . JavaScript
, , .
, .
. ,
- .
, . ,
deployAi rbags.
, - ?
, ;
, addPas s enger (

184 9 . -
, ). ,
JavaScript.
class Vehicle {
constructor ( ) {
t his . pas sengers = [ ] ;
consol e . log ( " Tpacopoe " ) ;

addPa s s enge r ( p ) {
this . p a s sengers . push ( p ) ;

class Car extends Vehicle


constructor ( )
super ( ) ;
nsl . lg ( " " ) ;

deployAirbags { ) {
console . log ( " ! ! ! " ) ;

, , - extends;
, Car Vehicle.
super ( ) . JavaScript,
. ;
, .
.
const v = new Vehicle ( } ;
v . addPassenge r ( " Frank" ) ;
v . addPas s enge r ( " Judy" ) ;
v . passengers ; 1 1 [ "Frank " , "Judy "J
const = new Car { ) ;
c . addPas s enger ( "Alice " ) ;
c . addPas s enge r ( " Cameron " } ;
c . passenge r s ; 11 [ "A l i ce " , "Cameron "]
v . deployAirbags ( } ; 11 =
c . deployAirbags ( } ; 1 1 " ! ! ! "

, deployAirbags , v.
, .
Car Vehicle, .

(polymorphism) -
,

- 1 85
, . -
- ,
. JavaScript , ..
( ).
, JavaScript .
JavaScript, ,
(duck typing). "
, , , , , , ,
': Car, ,
deployAi rbags, , Car.
, , .
JavaScript instanceof, ,
. , ,
prototype _proto_,
.
class Motorcycle extends Vehicle { }
const = new Car ( ) ;
const m = new Motorcyle ( ) ;
instanceof Car ; 1 1 true
instanceof Vehicl e ; 1 1 true
m instanceof Car; 1 1 false
m instanceof Motorcycle ; 1 1 true
m instanceof Vehicle ; 1 1 true

JavaScript
Obj ect. ,
instanceof Obj ect (
_proto_, ).
,

. toSt ring,
.

( }
, for . . . in. ,
,
hasOwnProperty .
obj obj . hasOwnProperty ( ) t rue, obj
, false, .
ES6 , ,
, . ,

1 86 9 . -
,
, hasOwnProperty,
. .
cla ss Super {
const ructor ( ) {
this . narne = ' Super ' ;
this . i s Super = true ;

1 1 , . . .

Super . prototyp e . sneaky = ' ! ' ;

class Sub extends Super


constructor ( ) {
super ( ) ;
this . narne ' Sub ' ;
t hi s . i sSub = t ru e ;

const obj = new Sub ( ) ;

for ( le t in obj ) {
console . log ( ' $ { p ) : $ { obj [ ] } ' +
( obj . hasOwnPropert y ( p ) ? ' ( ) ' ) ) ;

,
narne : Sub
i sSuper : true
i sSub : true
sneaky : ! ( )

name, i sSuper i sSub ,


( , , ,
). sneaky,
, .
, Obj ect . keys,
, .


Obj ect. ,
, Obj ect, .
toSt ring,

1 87
. toString
11 [ obj ect Obj ect ] 11, .
toString, ,
,
. , Car ,
toString , VIN.
c l a s s Car {
toString ( )
return ' $ { th i s . ma ke } $ { t hi s . mode l } : $ { this . vi n } ' ;
}
// . . .

toString Car
.

,
-
(multiple inheritance),
( , , ,
). (collision) .
,
g reet, ?
, .
,
. ,
, " " ( ,
, , , - ). ,
,
(interface), . (Car)
(Vehicle), (Insurale,
Container ..).
JavaScript - . ,
,
,
, ( - ).
-
(mixin). ""
. JavaScript
,
.

1 88 9 . -
"",
. ,
InsurancePol i cy.
addinsurancePolicy, get insurancePolicy ( ) i s insured.
, .
class I n s urancePolicy ( ) { }
function makeinsural e ( o ) {
o . addinsurancePolicy = function ( p ) { thi s . insurancePolicy = ; }
o . get insurancePolicy = function ( ) { return thi s . insurance Policy;
. i s i nsured = function ( ) { return ! ! thi s . insurancePo l i c y ; }

.
Car?
.
ma keinsural e ( Ca r ) ;

.
const carl new Car ( ) ;
=

carl . addinsurancePol icy ( new InsurancePolicy ( ) ) ; / /

", addinsurancePolicy
': . Car
. , :
, - .
, .
const carl new Car ( ) ;
=

make insurale ( car l ) ;


carl . addinsurancePo l i cy ( new I nsurancePol icy ( ) ) ; / /

, ma ke i n s urae
.
Car,
. , .
makeinsural e ( Car . prototype ) ;
const carl = new Car ( ) ;
carl . addi nsurancePo li cy ( new I n s urancePolicy ( ) ) ; / /

, Car.
JavaScript .
.
Car, InsurancePolicy
makeinsurae. ,
, Car.

, 1 89
: -
shi ft,
Car. , instanceof
, :
( addinsurancePolicy, , ,
).
, . ,
,
Car.
. .
class InsurancePol i cy ( ) { }
const ADD_POLICY =Symol ( ) ;
const GET_POLICY =Symol ( ) ;
const I S_ INSURED =Symol ( ) ;
const POLICY = Symol ( ) ;
function makeinsural e ( o ) {
o [ADD_POLICY] function ( p ) { thi s [ POLICY] = ; }
o [GET_POLICY] function ( ) { return this [ POLICY] ;
o [ I S INSURED] funct ion ( ) { return ! ! this [ POLI CY ] ;

, ,
Car.
, . ,
, , (
, POLI CY) .


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

1 90 9 . -
1 0

S : (map)
(set). ,
, ,
.

S, ,
,
.
.
, , ,
.
,
.
,
.
.


( - ). , ,
, .
const ul name : ' Cynthia ' };
const u2 name : ' Jackson ' };
const u name : ' Ol ive ' } ;
const u4 name : ' Jame s ' } ;

.
const u s e rRole s = new ( ) ;

set ( ) .
userRole s . set ( u l , ' Us er ' ) ;
userRole s . set ( u2 , ' Us er ' ) ;
userRole s . s e t ( u , ' Admin ' );
/ / . . .

set ( ) , .
userRole s
. se t ( u l , ' Us er ' )
. se t (u2 , ' Us er ' )
. se t ( u , ' Admin ' ) ;

.
const userRol e s new ( [
=

[ u l , ' Us er ' ] ,
[u2 , ' Us er ' ] ,
[ u , ' Admin ' ] ,
]);

, u2,
get ( ) .
userRole s . ge t ( u2 ) ; 1 1 "User "

get , ,
undefined. , has ( )
.
userRo l e s . ha s ( ul ) ; 1 1 t rue
userRole s . ge t ( u l ) ; 1 1 "User"
userRoles . ha s ( u4 ) ; 1 1 fa lse
userRole s . ge t ( u4 ) ; 1 1 undefined

s e t ( ) , ,
.
userRole s . ge t ( ul ) ; // ' User '
userRole s . set ( ul , ' Admin ' ) ;
userRole s . ge t ( ul ) ; / / 'Admin '

s i ze .
userRole s . s i z e ; 11 3

key s ( ) , values ( ) -
, entries ( ) - ,
- , - .
, for . . . of.

1 92 1 0.
for ( le t of userRole s . keys ( ) )
console . log ( u . name ) ;

for ( le t r of userRoles . value s ( } )


console . log ( r ) ;

for ( le t ur of userRol e s . entrie s ( ) )


console . log ( ' $ { ur [ ] . name } : $ { ur [ 1 ] } ' ) ;

1 1 :
1 1 , :
for ( le t [ u , r ] of userRoles . entr i e s ( ) )
console . log ( ' $ { u . name } : $ { r } ' ) ;

/ / entries () ,
-

/ / :
for ( le t [ u , r] of userRoles )
console . log ( ' $ { u . name ) : $ { r } ' ) ;

,
.
[. . . userRole s . va lues ( ) ] ; / / [ "User " , "User " , "Admin " ]

, delete ( ) .

userRoles . de l e t e ( u2 ) ;
userRoles . s i z e ; 11 2

, ,
, clear ( ) .
userRoles . clear ( ) ;
userRole s . s i z e ; 11


Weakap , .
.
Weakap .
Weakap .

JavaScript , - .
, , , JavaScript
, . Weakap
. - WeakMap (

1 93
, ,
).
WeakMap
.
const SecretHolder = ( functi on ( )
const secrets = new Weakap ( ) ;
return class {
s e t Secret ( secre t ) {
s ecret s . set ( th i s , secret ) ;

getSecret ( ) {
return secrets . ge t ( th is ) ;

}) () ;

WeakMap
(IIFE) , . IIFE
SecretHolde r, .
, setSecret,
- getSecret.
const new SecretHolder ( ) ;
const = new S e cretHolder ( ) ;

a . setSecret ( ' s e cret ' ) ;


b . s e t S e cret ( ' s ecret ' ) ;

a . getSecret ( ) ; 1 1 "secret "


b . getSecret ( ) ; 1 1 "secret "

,
SecretHolder !

(set) - , .
,
. , "User",
- " U s e r " , "Adrnin".
. -
.
Set.
const role s = new Set ( ) ;

1 94 10.
,
add ( ) .
role s . add ( " U s e r " ) ; / / [ 11User11 ]

, add ( ) -
.
rol e s . add ( "Admin " ) ; / / [ "User " , "Admin "

, Set s ize.
roles . si z e ; 11 2

, ,
, . ,
, .
role s . add ( " U s e r " ) ; 1 1 "Us er " , "Admin " ]
roles . si z e ; 11 2

, delete ( ) ,
true, , false - .
roles . delete ( "Admin " ) ; 1 1 true
role s ; / / [ "User " J
roles . de l et e ( "Admin " ) ; / / fa lse


,
. Weakap, WeakSet ,
.
-
, .
, WeakSet naught y (
), , .
const naughty = new WeakSet ( ) ;

const children [ =

name : " Suzy" } ,


name : " Derek" } ,
];

naught y . add ( children [ l ] ) ;

for ( let child of childre n )


if ( naughty . ha s ( child) )

1 95
console . log ( ' Yo $ { child . name } ! ' ) ;
else
console . log ( ' oap $ { ch i l d . name } ! ' ) ;

1
- JavaScript, S,
, .
, ,
. ,
! , ,
;
. , : "
, ?" - "':
.

1 "Breaking the Hablt" - Linkin Park. - . .

1 96 10.
1 1

, .
,
, . ,
- , .
- .
(exception handling) - ,
. ,
(error handling), ,
, .. , ,
.
()
. ,
,
, ,
.

: .

.

Error
JavaScript E rror,
( ). E r ror,
.
const err = new rrr ( ' ema il ' ) ;

E rror .
. ,
. ,
. ,
E rror. , @ ,
(. 1 7) .
functi on validateEmai l ( emai l )
return ema i l . match ( /@ / ) ?
emai l :
new rrr ( ' ema i l : $ { emai l } ' ) ;

, E rror,
typeof.
mes sage.
const emai l = " j ane@doe . com" ;

cons t validatedEmai l = validateEma i l ( emai l ) ;


i f ( validat edEmai l ins tanceof Error ) {
console . error ( ' Oa : $ { va l idatedEma i l . me s sage } ) ;
else {
nsl . lg ( ' ema i l : $ { validatedEmail } ' ) ;


E rror, ,
.


try tch
try . . . catch.
, "" (try) - ,
- , "" (catch). validateEma i l
,
@ ,
:
email . ,
emai l null, ( , )
. ,
.
try . . . catch.
const ema i l = nul l ; 1 1

try {

1 98 11.
const validatedEma i l = val idateEma i l ( emai l ) ;
i f ( va l idatedEma i l instanceof Error ) {
console . error ( ' Oa : $ { validatedEma i l . me s sage } ) ;
else {
nsl . lg ( ' ema i l : $ { va l i datedEmai l } ' ) ;

catch ( err) {
console . error ( ' Oa : $ { err . me s sage } ' ) ;

,
.
. ,
? ,

.
, catch,
; .. i f, va l idateEmai l ( ) ,
. t ry , ;
, , catch.
, catch , .


t ry . . . catch
, JavaScript (
match -, ).
,
.
, JavaScript
: ,
. throw Error.
catch E rror. ,
,
(, , ,
, throw
Error) .
, ,
, (
,
, ).

1 99
function b i llPay ( amount, , account )
i f ( amount > a ccount . balance )
throw new Error ( "Mao . " ) ;
accoun t . t rans fer ( payee , amount ) ;

t hrow
. account . t rans fer ,
.


, , ,
, - ..
JavaScript . ,
, , ,
, ,
. , , "':
, ,
(call stack).
,
, ,
, .
, ,
. , ,
.

. , JavaScript
. ( unhandled
exception) (uncaught exception),
. ,
, ,
, .
,
. ,
, ,
, ,
, ,
. ,
.

200 11.
JavaScript E rror
s tack, (
JavaScript, ). ,
, .
function ( ) {
console . log ( ' : ' ) ;
() ;
console . log ( ' a : ' ) ;

func t i on ( ) {
console . log ( ' : ' ) ;
() ;
console . log ( ' b : ' ) ;

func t i on ( ) {
console . log ( ' c : ' ) ;
throw new Error ( ' c ' ) ;
console . log ( ' c : ' ) ;

func t i on d ( ) {
console . log ( ' d : ' ) ;
() ;
console . log ( ' d : ' ) ;

try
();
catch ( err)
console . log ( err . s t a ck ) ;

try
d() ;
catch ( err)
console . log ( err . s t a c k ) ;

Firefox .
:
:
:
c@debugger eva l code : l : l
b@debugger eva l code : 8 : 4
a@debugger eva l code : 3 : 4
@ debugger eva l code : 2 3 : 4

201
d :
:
c@debugger eval code : l : l
d@debugger eval code : 1 8 : 4
@debugger eval code : 2 9 : 4

@ , "
" () ( ).
, . ,
, , , . ,
d.

try . . . catch . . . finally


t ry ,
.
, .
try ,
, t ry
( ,
). catch,
, . ,
finally, .

, fina l l y
console . log.
try
console . log ( " a m . . . " ) ;
throw new Error ( "Yc ! " ) ;
consol e . log ( " m . . . " ) ;
catch ( err) {
console . l o g ( " . . . " ) ;
finally {
console . log ( " . . . cea " ) ;
console . log ( " m " ) ;

throw ; ,
finally .

202 11.

, , ,
-
, . , ,
"", ,
. . ,
( ),
.
"" , catch,
JavaScript .

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

203
1 2

S :
(iterator) (generator). ,
.
: , . -
(iterae) : (
) ( ).
: , book
(), - , .
"Twinkle, Twinkle, Little Bat" (
, !1) (,
, ).
const book = [
" Twinkl e , twinkle , l it t l e bat ! " ,
" How I wonder what you ' re a t ! " ,
" Up above the world you f l y , " ,
" L i ke tea tray in the s ky . " ,
" Twinkl e , twink l e , l it t l e bat ! " ,
" How I wonder what you ' re at ! " ,
];

, book, ,
values.
const it = boo k . values ( ) ;

, ( it )
, . ,
. " ",
next , :
value, "", done,
t rue , . -
, ,
.

1 . - . .
i t . next () ; 11 va l u e : "Twinkle, t winkle, l i t tle ba t ! " , don e : fa lse }
i t . next () ; 11 va l u e : "How I wonder wha t you ' re a t ! " , done : fa lse }
i t . next () ; 11 va l u e : " above the wor ld you f1 , ", done : fa lse }
i t . next () ; 11 va l u e : "Like t ea tray in the sky. " done : fa lse }
'

i t . next () ; 11 va l u e : "Twinkl e , twinkle , l i t tl e ba t ! " , done : fa lse


i t . next () ; 11 va l u e : "How I wonder wha t you ' re a t ! " , done : fa lse }
i t . next () ; 11 va l u e : undefined, don e : true
i t . next () ; 11 va l u e : undefined, don e : true
i t . next () ; 11 va l u e : undefined , don e : true

, .
, next ,
, . :
, , , ?
, , .
, value unde fined
next .
,
, .2
,
, i t . next ( ) .
, i t .
, for for . . . of.
for : ,
,
. for . . .
? : for . . . of
t , . ,
. ,
for . . . of, while .
const it = book . values ( ) ;
l e t current = i t . next ( ) ;
while ( ! current . done ) {
console . log ( current . value ) ;
current = i t . next ( ) ;

, , .. ,
,
, .

2 ,
, " ':
done ; . ,
.

206 12.
const i t l = book . values ( ) ;
const i t 2 boo k . values ( ) ;
=

1 1

1 1 i tl :
i t l . next ( ) ; / / { va l u e : " Twinkle, twinkle, l i t t l e ba t ! ", don e : fa lse }
i t l . next ( ) ; / / { va l u e : "How I wonder wha t you ' re a t ! " , don e : fa lse }

1 1 i t 2 :
i t 2 . next ( ) ; / / { va l u e : " Twinkl e , t wink l e , l i t t l e ba t ! ", don e : false }

1 1 i tl :
i t l . next ( ) ; / / { va l u e : " above the world you fly, ", don e : false }


: - ,
. (iterator protocol)
. ,
r , .
.
class Log {
con s t ructor ( ) {
this . me s s ages [] ;

add ( me s sage ) {
this . messages . push ( { me s sage : mes sage , t ime stamp : Dat e . now ( ) });

".
(.. )? ,
log . me s s ages, ,
log , , ?
. ,
Symol . iterator, (..
next, value done),
! Log , Symol . i terator.
class Log {
con s t ructor ( ) {
this . me s sages [] ;

add (message ) {

207
t hi s . me s sages . push ( { mes sage : mes s a g e , timestamp : Date . now ( ) ));

[ S ymol . iterator ] ( ) {
return this . me s s a ge s . values ( ) ;

Log ,
.
const log = new L og ( ) ;
l g . dd ( " " ) ;
lg . dd ( " " ) ;
log . add ( " " ) ;
11. . .

/ / log, !
for ( le t entry of l o g ) {
console . log ( ' $ { entry . me s sage ) @ $ { entry . t imes t amp ) ' ) ;

,
mes s ages, .
class Log
// . . .

[ S ymol . iterat o r ] ( )
let i ;
=

const messages this . me s sage s ;


return {
next ( ) {
i f ( i >= mes s a ge s . lengt h )
return { value : unde fined, done : true } ;
return { value : message s [ i + + ] , done : false ) ;


: .
, .
:
. ,
. : -
. 1 1 :
1 + 1 2. 1 + 2 3. 2 + 3
5 .. .
1, 1 , 2, 3, 5 , 8 , 13, 21, 34, 55, 89, 144, . . .

208 n 1 2.
,
, ,
.
, t rue done:
c l a s s FibonacciSequence {
[ S ymol . iterato r ] ( ) {
let = , = 1 ;
return {
next ( )
let rval = { value : , done : false } ;
+= ;
= rva l . value ;
return rval ;

};

FibonacciSequence for . . . of,


. . . ,
! , break 10 .
const fib = new FibonacciSequence ( ) ;
l et i = ;
for ( let n o f f i b ) {
console . log ( n ) ;
i f ( ++ i > 9 ) brea k ;

(generator) - ,
.
, .
, . , ,
.
. -,
, . -,
.
.
(yield)
.
, .
. next .

209
JavaScript function;
.
, yield return.
,
.
funct ion* rainbow ( ) { // ,
yield ' ' ;
yield ' ' ;
yield ' ' ;
yield ' ' ;
yield ' ' ;
yield ' ' ;
yield ' ' ;

, . ,
. ,
.
=
const it rainbow ( ) ;
i t . next ( ) ; 1 1 va l u e : " ", don e : false }
i t . next ( ) ; 1 1 va lue : " ", don e : false
i t . next ( ) ; 1 1 va lue : " " , don e : fa lse }
i t . next ( ) ; 1 1 val ue : " " , don e : fa lse
i t . next ( ) ; 1 1 va lue : " " , don e : fa lse }
i t . next ( ) ; 1 1 va lue : " " , don e : fa lse }
i t . next ( ) ; 1 1 va l ue : " ", don e : fa lse
i t . next ( ) ; 1 1 va l ue : undefined, done : true }

rainbow ,
for . . . of.
for ( let color o f rainbow ( ) )
console . log ( color) ;

yield
,
. yield.
, , yield
- . ( ),
next .
, .
function* interrogate ( ) {
const name = yield " ? " ;

210 12.
const color = yield " ? " ;
return ' $ { name } $ { co l o r } . ' ;

, ,
. next,
. yield,
.
next,
name , next.
, .
const it = interrogate ( ) ;
i t . next ( ) ; / / { va l u e : " ? " , don e : fa lse }
i t . next ( ' ' ) ; / / { va l u e : " ? " don e : fa l s e }
1

i t . nt ( ' ' ) ; / / { val u e : " . " , done : true }


. 12. 1 .
1. ; .

func t i on* interrogate ( ) { const i t int errogate ( ) ;


c on s t narne = yield ' ? ' ;
const color = yield ' ? ' ;
return ' $ { narne } $ ( color} . ' ;

2 . narne=unde f ined; ' ? ' ; .

func t i on* interrogate ( ) {


const narne = y i e l d ' ? ' ; i t . next ( ) ;
const color = yield ' ? ' ;
return ' $ ( narne } $ { color } . ' ;

. nm= ' " ; " ? ' ; .

func t i on* interrogate ( ) {


const narne = yield ' ? ' ;
const color = y i e l d ' ? ' ; i t . next ( ' ' ) ;
return ' $ { narne } $ ( color } . ' ;

4 . lr= ' ' ; ' . ' ;


.

func t i on* interrogate ( )


const narne = y i e l d ' ? ' ;
const color = y i e l d/' Kao ? ' ; 1111( 1
return ' $ ( narne } $ { co l or } . ' ; ---i- i t . t ( ' ) ;

. 12. 1 :

211
, ;
. ,
,
.

, ;
function * .

return
yield ,
. return
t rue done. , ,
.
funct ion* ( )
yield ' ' ;
yield ' ' ;
return ' ' ;

=
const it count ( ) ;
i t . next ( ) ; 1 1 { va l ue : ' , ' don e : fa lse }
,
i t . next ( ) ; 1 1 { va l ue : ' ' done : fa lse }
i t . next ( ) ; 11 va l u e : ' , , done : true }

, ,
value,
done - t rue. , for . . . of, ""
.
11 " " " " , " "
for ( le t 1 of ( ) )
console . log ( l ) ;

return
.
yield; return
.
return .

212 12.

,
.
, S,
.

:
, .
,
. 14 ,
.

213
1 3

JavaScript ,
:
( , , : ).
6,
, .
:
. ( ) -
.


(subroutie) -
.
.
,
, .

(procedure),
(routie), (subprogram), (macro)
(callae uit).
, JavaScript
(subroutie). (
). ,
.

,
.
, .
const year = new Date ( ) . ge tFul lYear ( ) ;
i f ( year % 4 ! == 0 ) console . log ( ' $ { ye a r } . ' )
e l s e i f ( year % 1 0 0 ! = 0 ) console . log ( ' $ { year } . ' )
e l s e i f ( year % 4 ! = ) consol e . l o g ( ' $ { year } . ' )
e l s e conso l e . log ( ' { $ year } ' ) ;

, 10 1 00 .
, ,
;
! ,
. JavaScript .
function printLeapYearStatus ( ) {
const year = new Date ( ) . getFullYear ( ) ;
i f ( year % 4 ! == ) console . log ( ' $ { year } . ' )
e l s e i f ( year % 1 0 0 ! = 0 ) console . log ( ' $ { ye a r } . ' )
e l s e i f ( year % 4 0 0 ! = 0 ) console . log ( ' $ { year } . ' )
e l s e console . log ( ' { $ year } . ' ) ;

1- () printLeap
YearStatus. .
, :
printLeapYearStatus. getLeapYearS tatus leapYearStatus,
leapYea r? , :
.
- , . - JavaScript,
, . - ( ).
, , ,
. ,
. , .
, calculateCurrentLeapYearStatusAn
dPrintToConsole,
. .

,
printLeapYea rStatus -
:
, .
, ,
, .

, .

21 13.
printLeapYearStatus , ,
, .
L- ,
.
,
, .
, ( !) ,
, .
funct ion i sCurrentYearLeapYear ( ) {
const year = new Date ( ) . ge t FullYear ( ) ;
i f ( year % 4 ! == 0 ) return false ;
e l s e i f ( year % 1 0 0 ! = 0 ) return true ;
e l s e i f ( year % 4 0 0 ! = 0 ) return false ;
e l s e return true ;

,
.
const days inMonth =
( 3 1 , isCurrentYearLeapYear ( ) ? 2 9 : 2 8 , 3 1 , 3 0 , 3 1 , 3 0 ,
31, 31, 30, 31, 30, 31] ;
i f ( i sCurrentYearLeapYea r ( ) ) console . log ( ' Ceac . ' ) ;

,
. ,
(
), is.
crrent (). ?
. , ,
3 1 2016 , 1 2017 .
-

. . .
,
, . . . .
, (relation)
. .
, ,
(pure function). (, Haskell)
.
, ?
,
. i sCurrentYearLeapYea r

, 21 7
, , ,
( t rue, -
false). -, (side effect).
, .
(
). .
const colors = [ ' ' , ' ' , ' ' , ' ' ,
' ' , ' ' , ' ' ] ;
let colorindex = - 1 ;
function getNextRa inbowColor ( ) {
i f ( ++colorindex >= colors . length) colorindex ;
return colors [ colorindex ] ;

getNextRainbowColor ,
. :
(
, - ),
( colorindex ) .
colorindex ; getNextRainbowColor
, .
.
? !
function i s LeapYear ( year ) {
i f ( year % 4 ! == 0 ) return fal s e ;
e l s e i f ( year % 1 0 0 ! = 0 ) return true ;
e l s e i f ( year % 4 0 0 ! = 0 ) return false ;
e l s e return true ;


, , .
getNextRainbowColor .
, .
const getNextRainbowColor = ( function ( ) {
const colors = [ ' ' , ' ' , ' ' , ' ' ,
' ' , ' ' , ' ' ] ;
let colorindex = - 1 ;
return func t i on ( ) {
i f ( ++colorindex >= colors . lengt h ) colorindex ;
return colors [ co lo r i nde x ] ;
};
}) () ;

218 13.
,
,
. ,
. ,
, , (
1 8).
set Interval ( function ( ) {
document . querySelector ( ' . rainbow ' )
. s tyle [ ' background-color ' ] = getNextRainbowColor ( ) ;
} 500) ;
1

, , , :
HTML rainbow .
, - getNextRainbowColor ( ) ,
! "
': ,
, .
funct ion getRainbowi terator ( ) {
const colors = [ ' ' , ' ' , ' ' , ' ' ,
' ' , ' ' , ' ' ] ;
let colorindex =-1;
return {
next ( ) !
i f ( ++colorindex > = colors . l engt h ) colorindex = ;
return { value : colors [ colorindex ] , done : false } ;

};

getRainbow i t e ra tor :
(), .
, .
const rainbowi terator = getRainbowiterator ( ) ;
s e t i n terva l ( funct ion ( ) {
document . querySelector ( ' . ra inbow ' )
. style [ ' background-co lor ' ]= rainbowit erator . next ( ) . va lue ;
} 500 ) ;
/

, :
next ( ) r , ,
next ( ) , . ,
, .
getRainbowlterator ,
, .

, 219
?
, , (
, q ),
" ?1 ?"
JavaScript,
, . ?
, :
.
- .


,
: DRY (don't repeat yourself - ). ,
, ( - ""), ,
, , -
. " ': -
, ,
.

-
"" .
: " !"
, : " ?"
: "
, ':
,
, . -
, ,
, , . ,
, 99% , 1 % .
, - :
, ,
.
, ,
. ""
.
.
, ,

1 "So What" Pink 2008 . - . .

220 13.
. ,
, .
- ,
9, ,
.


JavaScript Function.
, ;
. , ,
v, typeof v " function".
, , v :
" obj ect " . typeo f v
. , , , v , -

v instanceof Obj ect . ,


, typeof.




(IIFE) 6 , .
( 14) ,
IIFE .
IIFE
,
. ,
5 ( " ! " ).
setTimeout, (
) ( ). ,
" ! " 1 ,5 .
s e tTimeout ( funct ion ( ) { console . log ( " ! " ) ; } , 1500) ;

, , .
var i ;
for ( i=5 ; i >= O ; i - - ) {
setTimeout ( funct ion ( )
console . log ( i===O ? " ! " i) ;
}, ( 5-i ) * 1 0 0 0 ) ;

221
, var l et .
, IIFE . 5, 4 , 3, 2, 1 , " ! ",
-
. 1 .

, , setTimeout, ,
. , i, 5,
1 . , .
- ..

, i - 1 .
, ( let),
, , ,
. ,
( 14).

.
, i "
" ( ) .
.
function loopBody ( i) {
setTimeout ( function ( )
console . lo g ( i===O ? " ! " i) ;
} ' ( 5- i ) * 1 0 0 0 ) ;

var i ;
for ( i= S ; i > O ; i - - )
loopBody ( i ) ;

loopBody. , JavaScript
. ,
i, .
5, - 4 .. ,
(i): ,
(
loopBody).
,
, . IIFE:
, , ,
. IIFE.
var i ;
for ( i=S ; i > O ; i-- ) {
( function ( i ) {
setTimeout ( funct ion ( )
console . log ( i===O ? " ! " i) ;

222 1 3.
} , ( 5- i ) * 1 0 0 0 ) ;
} ) (i) ;

! , ,
: , ,
(. 1 3. 1 ) .

var i ;
for ( i=S ; i>O ; i-- ) {
( function ( i ) {
setTimeout ( function ( ) {
var i ; console . log ( i===O ? " ! " i) ;
for ( i=S ; i>O ; i-- ) { } , ( 5-i ) * l O O O ) ;
loopBody ( i ) ; }) (i) ;
} }

. 13. 1 .


, . -
.
for ( let i=5 ; i > O ; i - - ) (
setTimeout ( function ( )
console . log ( i===O ? " ! " i) ;
} , (5-i) * 1 00 0 ) ;

, let
for. for, ,
. , let JavaScript,
, i .
, , s e t T ime out, ,

.


, 2
: , ,
.

2 "Another Cup of Coffee" Mike And The Mechanics. - . .

223
, .
, -
(, , ).
,
,
, .
, (
). , , .
. . . , , .
, . ,
: 2 , 1 ..
, .
: ( - ).
( ),
, ,
: , ,
, ..
, , - .
, , ,
? , , .
, ,
.
(, , ).
(. 9).
.
.
,
.
? ,
, , "
?" ,
.
:
. ,
.
, .
- , ,
.

224 1 3.
function addThreeSquareAddFiveTakeSquareRoot ( x ) {
1 1 , ?
return Math . sqrt ( Math . pow ( x+ , 2 ) + 5 ) ;

/ /
const answer = ( addThreeSquareAddFiveTakeSquareRoot ( S ) +
addThreeSquareAddFiveTakeSquareRoot ( 2 ) ) /
addThreeSquareAddFiveTakeSqureRoot ( 7 ) ;

1 1
const f = addThreeSquareAddFiveT a ke SquareRoot ;
const answer = ( f ( S ) + f ( 2 ) ) / f ( 7 ) ;

, ""
addThree Squa reAddFi veTakeSquareRoot. ,
, f , addThreeSquareAd
dFiveTakeSquareRoot, . ,
(, f ( 5 ) ), ,
f , .
, ,
.
(namespacing), Node
(. 20), .
const Money = require ( ' math-money ' ) ; / / require - Node
/ /
const oneDollar Mone y . Dollar ( l ) ;
=

/ / , "Money . Dollar " :


const Dollar =Money . Do l l a r ;
c o n s t twoDollars = Dollar ( 2 ) ;
/ / : oneDollar twoDollars -

(aliasing) ,
Mone y . Dollar Dol lar, .
, ,
.


,
,
. - (pipeline),
, .
, .

225
? . ?
.
- .
, ""
. .
const s in = Math . si n ;
const c o s = Math . co s ;
const theta = Math . PI / 4 ;
const zoom = 2 ;
const offset = [ 1 , - 3 ] ;

const pipeline = [
function rotate ( p )
return {
: . * cos ( t heta ) - . * s i n ( theta ) ,
: . * sin ( t he t a ) + . * cos ( theta ) ,
};
},
functi on scale ( p ) {
return { : . * zoom, : . * zoom } ;
},
funct ion translat e ( p )
return { : . + offset [ O ] , : . + offset [ l ] ; } ;
},
];

/ / pipeline -
/ / , :

cons t = { : 1 , : 1 } ;
let 2 = ;
for ( l e t i=O ; i<pipe line . length; i + + ) {
2 = pipeline [ i ] ( 2 ) ;

/ / 2 - pl , 45 (pi/ 4 )
1 1 , 2 ,
/ / 1 3

, ,
.
: pipel ine [ i ]
i , .
( ). ,
. , -
.

226 1 .

: ,
. ,
, ,
.


:
setTirneout fo rEach.
,
.
( (callback))
. ,
. 1 4.
- ,
; ""
. sum,
( ,
, ).
, ,
'? , sumOfSquares " "
, '?
. sum.
function sum ( arr, f ) {
/ / , "
11 " ,
i f ( t ype o f f ! = ' funct ion ' ) f = => ;

return arr . reduce ( ( a , ) = > += f ( x ) , ) ;

sum ( [ 1 , 2 , 3 ] ) ; 1 1
sum ( [ l , 2 , 3 ] , => * ) ; / / 1 4
s um ( [ l , 2 , 3 ] , = > Math . pow ( x , 3 ) ) ; 1 1 3 6

sum . . . ,
. '? . ,
4,233'? . ,
sum, ..
. f
unde fined, , .
, , , " ':

227
. , 5,
5, ..
(,
), ,
"" .


, ,
, .
: , ( ),
, , , -.
, , ,
- , ,
.
, sum, ,
( !) , ,
. , ,
sumOfSqua res, ?
, ..
. ,
, . ( ,
, API,
sum, .)
,
.
function sumOfSquares ( arr) {
return sum ( arr, => * ) ;

, , , ,
, - ,
? ,
.
funct i on newSumme r ( f ) {
return arr => sum ( ar r , f ) ;

, newSumme r, sum,
, .
,
.

228 1 3.
const sumOfSquares = newSumme r ( x => * ) ;
const sumOfCube s = newSummer ( x = > Math . pow ( x , 3 ) ) ;
sumOfSquares ( [ 1 , 2 , 3 ] ) ; / / 1 4
sumOfCube s ( [ l , 2 , 3 ] ) ; / / 3 6

,
,
(currying) ,
( Haskell Curry).

.
,
Express ( - JavaScript).

-
(recursion), .
,
.
: .
, ,
.
1. , . 3.
2. . . 1 .
3 . !
, ;
. , .
function findNeedle ( haystack) {
i f ( haystac k . length === 0 ) return " ! " ;
i f ( ha ystac k . shift ( ) === ' ' ) return " ! "
r e turn findNeedle ( ha ystack ) ; / /

findNeedle ( [ ' ' , ' ' , ' ' , ' ' , ' ' , ' ' , ' ' ] ) ;

,
: haystack ( ), -
(!) ( -
, ; ,
Array . prototype . shi ft ).

229
,
(stopping condition) ; ,
JavaScript , (
). findNeedle
: .
,
.
, :
. - ,
. 4!
4 3 2 1 24. .
=

function fact ( n ) {
i f ( n === 1 ) return 1 ;
return n * fact ( n - 1 ) ;

(n === 1), , ,
n . 1 (
,
, , , , ).



, ML, Haskell, Clojure F#,
. , , r,

(, , , , ).
,
, " ?" ,
. :
. : ?
,
. ,
, , -
.

230 1 .
1 4

1 ,
. , ,
, : ,
, , . -
:
JavaScript .
JavaScript (single-threaded).
, JavaScript - .
(
, ),
, ,
, - , -
, (
(preemptive multitasking)).
, , ,
.
, JavaScript
,
, .
: ,
,
. ,
, .
JavaScript
. JavaScript (
)
. , JavaScript
: ,
. ,
, , , , .
- .
:
( MDN ),
.
, (
, ).
,
.
(, Ajax).
(, ..).
(,
).

r
,
, - ,
. ,
(
, ).
: , ,
. ,
; . ,
, .
: , , ,
.
,
, .


(callback) - JavaScript,

. - ,
.
: JavaScript. ,

(, , ).
(, ) .

232 14.

setTimeout,
.
cons o l e . log ( " :"+ new Date ( ) ) ;
function f ( ) {
console . log ( "oce : " + new Date ( ) ) ;

set Timeout ( f , 6 0 * 1 0 0 0 ) ; / /
console . log ( " o setTimeout ! " ) ;
console . log ( " ! " ) ;

(
), .
: Sun Aug 02 2 0 1 5 1 7 : 1 1 : 32 GMT- 0 7 0 0 ( Pa c i f i c Daylight Time )
setTimeout !
!
: Sun Aug 02 2 0 1 5 1 7 : 1 2 : 32 GMT - 0 7 0 0 ( Pa c i f i c Daylight T ime )

'l
, , .
( ), ,
. , .
: Sun Aug 0 2 2 0 1 5 1 7 : 1 1 : 32 GMT- 0 7 0 0 ( Pa c i f i c Daylight Time )
: Sun Aug 0 2 2 0 1 5 1 7 : 1 2 : 3 2 GMT- 0 7 0 0 ( Pa c i f i c Daylight Time )
setTimeout !
!

. . . !
, .
JavaScript ,
60 , ,
, . ""
: ,
.. , .
.

setTimeout.
, .
setTimeout ( funct ion ( ) {
console . log ( "oce : " + new Date ( ) ) ;
} , 60*1000 ) ;

setTimeout ,
.

233
, , , -
, . ,
setT imeout (
set interval ) . ,
!

setinterval clearinterval
setTimeout,
, set interval,

clea r i nte rva l. , 5
, 1 0 , .
const start = new Date ( ) ;
let i=O ;
const interva l i d = s e t i nt erval ( function ( )
l e t now = new Date ( ) ;
i f ( now . getMinutes ( ) ! == start . getMinut e s ( ) 1 1 ++i> l O )
return clearint e rva l ( interval i d ) ;
console . log ( ' $ { i } : $ { now } ' ) ;
} 5*1000 ) ;
'

, setinterval ,
.
c l ea rTimeout,
.

s e t T ime out, s et in t e rval c l e a r inte rva l


(window global Node).


( )
, -
. , ,
: , ( ),
, - .
,
, . countdown.
- 5- .
funct ion countdown ( } {
let i ; / / , l e t for

234 1 4.
nsl . lg ( " : " ) ;
for ( i=5 ; i>=O ; i - - ) {
setTimeout ( function ( )
console . log ( i===O ? " ! " i) ;
} , (5-i) *lOOO) ;

countdown ( ) ;

. , , ,
- . , 5 .
- 1 " ! " .
, var; let,
for, : for
, i 1 ,
-

. , , , i -1.
,
. countdown,
, i. () ,
for, i.
, for i,
. ( ( 5- i ) * 1 ),
: , 1 000, 2 0 0 0
- - -

.. , .
s etTimeout . ,
. -
, setTimeout, .
, ,
(IIFE), , i
for.
function countdown ( ) {
nsl . lg ( " : " ) ;
for ( le t i=5 ; i >= O ; i - - ) { / / i
setTimeout ( funct ion ( )
console . log ( i===O ? " ! " : i ) ;
} ' (5-i) *1000) ;

countdown ( ) ;

, ,
:
( ). -
,

235
. ,
.


Node

(error-first callback). , ,
, ,
.

. nul l unde fined, .
,
, , , -
.
Node, ,
.
const fs = require ( ' fs ' ) ;

const fname = ' may_or_may_not_exi s t . txt ' ;


f s . readFile ( fname , function ( er r , d a t a ) {
i f { err) return console . error ( ' Oa $ { fname } : $ { err . me s
sage } ' ) ;
console . log ( ' $ { fname } : $ { da t a } ' ) ;
});

, , -
e r r . , , ,
, (
cons o l e . error ,
, ).
,
, , , , ,
, , .
,
, ,
. ,
, ,
.
.
- -
Node ( ),

236 14.
, -
, .


,
: ,
.
, Node,
, 60 ,
.
const fs = require ( ' fs ' ) ;

fs . readFile ( ' a . txt ' , function ( er r , dataA) {


i f ( err) console . error ( err ) ;
fs . readFile ( ' b . txt ' , funct ion ( err , dataB)
i f ( er r ) cons o l e . error ( err) ;
f s . readFile ( ' c . txt ' , funct ion ( er r , dataC )
i f ( err) console . error ( err) ;
setTimeout ( function ( ) {
fs . writeFile ( ' d . txt ' , dataA+dataB+dataC, function ( er r ) {
i f ( err) console . error ( err ) ;
});
} , 60*1000 ) ;
});
});
});

m (callback hell).
, .
. , , -

, ,
. .
const fs = require ( ' fs ' ) ;
funct i on readSket chyFil e ( ) {
try {
fs . readFil e ( ' does_not_exist . txt ' , function ( er r , data ) {
i f ( err) throw e r r ;
});
catch ( er r ) {
nsl . lg ( ' : ,
m ' ) ;

readS ketchyFi le ( ) ;
,
, .
. . ,
, -
. , try . . . catch
. t ry . . . catch readSketchyFi le,
, fs . readFi le
.
, ,
( !).
, ,
.
,

. .

1 (promise)
. ( ),
" " .
;
.
,
,
, ,
.
:
, P rorni s e.
: (fulfilled)
( ) (rejected) ( ).
, (
, ) .

1 MDN promise .
, , - !
, , JavaScript
, .
!
, .
.
promise. MDN
. - . .

238 1 4.
, ;
, .
, , (settled).

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


:
Promi s e ,
resolve () rej ec t () ( ,
!). countdown,
( 5-
) , ,
.
function countdown ( seconds )
return new Promise ( function ( resol ve , rej e c t ) {
for ( let i=seconds ; i>= O ; i - - )
setTimeout ( function ( ) {
i f ( i> O ) console . log ( i + ' . . );
. '

e l s e re solve ( consol e . log ( " Cap ! " ) ) ;


} ( seconds- i ) * 1 0 0 0 ) ;
,

});

. ,
, , - .
,
-, DOM
. ...
. , resol ve ( rej ect) .
"-! resolve ...
': resol ve
re j ect ...
. , ,

n 239
- (
).


, countdown.
: countdown ( 5) .

.
? .
countdown ( 5 ) . then (
function ( ) {
nsl . lg ( " " ) ;
},
function ( err) {
consol e . log ( " Oa : " + err . me s s a ge ) ;

);


; ( then) .
:
(.. ), -
(.. ).
. catch.
, (
, ).
cons t = countdown ( 5 ) ;
p . then ( function ( ) {
nsl . lg ( " " ) ;
});
p . catch ( functi on ( e rr ) {
consol e . log ( " Oa : " + err . me s sage ) ;
});

countdown ,
. , ,
1 3 .
funct ion countdown ( se conds ) {
return new Promi s e ( funct ion ( re s olve , rej ect ) {
for ( le t i=seconds ; i>=O ; i - - ) {
s e t T imeout ( function ( ) {
i f ( i=== l ) return r e j ect ( new rrr ( "
! " ) ) ;

240 1 4.
}) ;

.
. ,
, 1 3, . 13
, 1 3. ...
! rej ect ( resol ve) ;
.
, countdown .
,
( ), . ,
. .

, , , ( !)
.
, , . ,
" 50%': 2
, ,
JavaScript,
, .

(event) - ,
JavaScript. : ()
, , ( "") ,
. ?
, ! , Node
. , jQuery
. countdown,
EventEmitter Node. EventEmit t e r
, countdown, .
, countdown Countdown.
const EventEmit t e r = require ( ' events ' ) . EventEmi t t e r ;

class Countdown extends EventEmit ter {


con s t ructor ( s econd s , superst i t i ous )

2 , Q.

241
super ( ) ;
t hi s . se conds = s econds ;
t hi s . super s t i t ious = ! ! super s t i t i ou s ;

go ( ) {
const countdown = t hi s ;
return new Promi s e ( funct ion ( res olve , r e j ect ) {
for ( le t i=countdown . seconds ; i>= O ; i-- ) {
setTimeout ( function ( ) {
i f ( countdown . super s t i t ious & & i=== 1 3 )
return rej ect ( new rrr ( " ! " ) ) ;
countdown . emit ( ' ti ck ' , i ) ;
i f ( i=== O ) resolve ( ) ;
} , ( countdown . se conds - i ) * 1 0 0 0 ) ;

});

Count down EventEmitter,


. go - ,
. , ,
go, - this countdown. ,
this
, . ,
this - ,
. , thi s,
.
countdown . emi t ( ' t i ck ' , i ) . ,
t i c k (
; , "tick" ), . ,
, .
const = new Countdown ( S ) ;

c . on ( ' tick ' , function ( i ) {


i f ( i > O ) console . log ( i + ' . . . );
'

});

c . go ( )
. then ( funct ion ( )
console . log ( ' Cap ! ' ) ;
})
. catch ( funct ion ( err) {
consol e . error ( er r . mes sage ) ;
})

242 1 4.
on EventEmi tter
. ti ck.
t i c k , . go,
. ,
" ! " . , " ! "
t ick, .
, , ,
countdown, .

, .
-
Countdown, 1 3,
.
const = new Countdown ( l 5 , t rue )

. on ( ' tick ' , function ( i ) { / / , " " ' '


i f ( i > O ) console . log ( i + ' . . . ) ;
'

});

. go ( )
. then ( funct ion ( )
console . log ( ' ! ' ) ;
})
. catch ( function ( er r ) {
console . error ( err . me s sage ) ;
})

t i c k
( ).
, . ,
"" ,
1 3 ,
! , ,
,
.
const EventEmit t e r = require ( ' events ' ) . EventEmitte r ;

class Countdown extends EventEmit t e r {


constructor ( seconds , supers t i t ious )
supe r ( ) ;
thi s . s econds =seconds ;
thi s . supe r s t i t ious 1 ! supe r s t i t ious ;
=

go ( ) {

243
const countdown = t hi s ;
const timeout ids = [ ] ;
return new Promi s e ( funct ion ( re solve , rej ect ) {
for ( le t i=countdown . seconds ; i >= O ; i - - ) {
t imeout ids . push ( setTimeout ( function ( ) {
i f ( countdown . supe r s t i t ious && i=== l )
/ /
t imeout ids . forEach ( clearTimeout ) ;
return rej ect ( new rrr ( "
! " ) ) ;

countdown . emit ( ' t ick ' , i ) ;


i f ( i=== O ) resolve ( ) ;
}, ( countdown . seconds - i ) * 1 0 0 0 ) ) ;

});


, z (chained),
.. ,
, ". ..
launch, .
funct ion launch ( ) {
return new Promi s e ( funct i on ( re s o lve , rej ect ) {
console . log ( " oexa ! " ) ;
setTimeout ( function ( ) {
resolve ( "Ha ! " ) ;
} , 2*1000) ; / /
});

.
const = new Countdown ( 5 )
. on ( ' t ick ' , i => console . log ( i + ' . . . ) ) ; '

c . go ( )
. then ( launch )
. then ( functi on ( ms g )
console . log (msg ) ;
})
. catch ( funct ion ( err) {
console . error ( " Xco, . . . . " ) ;
})

244 1 4.
,
; - ,
catch.
1 5- ; ,
launch .



, ,
, ( ..
resol ve rej ect).
, . . .
.

;
, . , ,
" ''. ,
10 , 1 - .
launch . ,
, .
function launch { ) {
return new Promi s e { funct ion ( resolve, rej e c t ) {
i f { Math . random { ) < 0 . 5 ) return ; / /
console . l og { " oexa ! " ) ;
setTimeout { funct ion { ) {
resolve { "Ha ! " ) ;
} , 2* 1 0 00 ) ; / /
});

:
rej ect .
. , ,
, ". , .
, .
function addTimeout { fn , t imeout ) {
i f { t imeout=== unde fined) t imeout = 1 0 0 0 ; / /
return functi on { . . . args ) {
return new Promi s e { funct ion ( re solve , r e j e c t ) {
const t i d setTimeout { re j e c t , t imeout ,
=

new rrr { " " ) ) ;


fn { . . . arg s )

245
"." , ,
, ,
... !': :

. -
"" . :
, .
, 1 (
?). ,
1 1 .
. go ( )
. then ( addTimeout ( launch, 4 * 1 0 0 0 ) )
. then ( function (msg) {
cons o l e . log (msg) ;
})
. ca t ch ( funct ion ( er r )
(
console . error ( "Xco, : " + err . me s sage ) ;
});

,
launch .

1 2,
.
, , ,
JavaScript.
: ,
. ,
: 1, 2, 3 ..
, .

246 1 4.

?
.
" ":
,
.
.
dataA ' a . txt '
dataB = ' b . txt '
dataC = ' c . txt '
6 0
dataA + dataB + dataC ' d . txt '

, ...
:
.
, , -
Node .
nfcall (Node function call - Node).
function nfcall ( f , . . . args ) {
return new Promise ( funct ion ( re s o lve , rej ect ) {
f . cal l ( nu l l , . . . args , function ( err, . . . args )
i f ( er r ) return rej ect ( err) ;
resolve ( args . length<2 ? args [ O ] : args ) ;
});
}) ;

nfca l l
Q ( ).
,
Q. , -
, .
nfca l l , "
" .

, Node, ,
.
s etT ime out, ...
Node,
. ptimeout (promise
timeout - ).

247
function pt imeout (delay) {
return new Promi s e ( function ( re solve , rej ect ) {
s e tTimeout { resolve , del a y ) ;
}) ;

, , - (generator runner).
, .
,
, ,
. g run (generator run -
).
function grun ( g ) {
const i t = g ( ) ;
( function i terate ( va l )
const = i t . next ( va l ) ;
if ( ! . done ) {
i f ( x . va lue instanceof Promi s e ) {
x . va lue . then ( i t e rate ) . ca t ch ( err => i t . throw ( err ) ) ;
else {
setTimeout ( iterate , , x . value ) ;

} ) () ;

g run runGenerator,
(Kyle Simpson)
.
.

.
, . 6, ,
yie ld, , next
. .
,
. , ,
. "
setT irneout i te rate?" ,
(
JavaScript ).
" !" " ?"
. nfcall (

248 1 4.
Node)
(), grun
( ES7 awai t, , ,
grun ). ,
, , .
" " ?
.
funct i on * theFuturei sNow ( )
const dataA yield nfcall ( f s . readFi l e , ' . txt ' ) ;
const dataB = yield nfcall ( fs . readFile , ' b . txt ' ) ;
const dataC = y i e ld nfcall ( fs . r eadFile , ' c . txt ' ) ;
yield pt imeout ( 6 0 * 1 0 0 0 ) ;
yield nfcall ( fs . writeFile , ' d . t xt ' , dataA+dataB+dataC) ;

, , ?
, , ,
. .
grun ( theFuture i sNow ) ;

?
( ) ,
, ."
, ,
, g run.
: theFuturei sNow
.
.
, . ''
?"
, JavaScript,
. ,
, ,

.
:
, .
(, ) . P romi s e
a l l , (resolves), (resolve)
". ,

249
. ,
Promise . a l l .
function* theFuture i sNow ( )
const data yield Promis e . al l ( [
=

nfca l l ( fs . readFi l e , ' . t xt ' ) ,


nfcal l ( f s . readF i l e , ' b . txt ' ) ,
nfcal l ( fs . readFil e , ' . txt ' ) ,
]);
yield p t imeout ( 60 * 1 0 0 0 ) ;
yield n f c a l l ( fs . wr i t e F i l e , ' d . txt ' , data [ O ] +data [ l ] +data [ 2 ] ) ;

, Promi s e . a l l , ,

. , . txt
, . txt, data [ ] . txt,
da ta [ 2 ] - . txt.
,
Promi s e . a l l ( ) , ,
,
, .
: ,
. , ,
60 , ,
, . , ,
, 60 ,
-
Promi s e . a l l .


, grun,
,
. .
. -, ,
-,
yield, theFuturei sNow.


,
try/ catch.
,

250 14.
.
.
,
, t ry/ cat ch.
theFuturei sNow
.
function * theFuture i sNow ( )
let dat a ;
try
data = yield Promise . al l ( [
nfcall ( fs . readFile , ' . t xt ' ) ,
nfcall ( fs . readFi l e , ' . t xt ' ) ,
nfcall ( fs . readFi l e , ' . txt ' ) ,
]);
catch ( er r ) {
consol e . error ( " Oa : " + err . message ) ;
throw e r r ;

y i e l d p t imeout ( 60 * 1 0 0 0 ) ;
try {
yield nfcall ( fs . writ e F i l e , ' d . txt ' , data [ 0 ] +data [ 1 ] +data [ 2 ] ) ;
catch ( er r ) {
console . error ( "Oa : " + err . me s s age ) ;
throw e r r ;

, try . . .
catch catch
,
,
, .


(
, )
JavaScript. .
JavaScript
.
;
then catch.

.
,
(
).
, .
,
,
.

,
Promise . a l l .
; .

Node ; Q.
,
.


, JavaScript
, .
JavaScript.

252 1 4.
1 5

.
, JavaScript Date ( )
. -
Moment . j s,
Date,
.
: JavaScript Date
Netscape (Ken Smith); , ,
JavaScript j ava . util . Date Java. ,
, JavaScript Java,
: - ,
- , " , Date
':
" " ,
"':
1 2:00 .

, , Unix
:
- , , 1,
. .
.
- : .
, . (
) , .

. : ", ,
1437595200?" ( 1437595200 - , 22 20 1 5 , 1
.) ,
, :
1 1 970 , 00:00:00 UTC.
, , , (TZ),
, , 7 , 7 - .
, .

- .
JavaScript Date ( Moment . j s ) , .

( - UTC), . UTC
( ) (Greenwich Mean
Time - GMT). , ,
.
UTC. " "? ?
. , - .
, - .
, , .
JavaScript new Date ( ) , .
Sat Jul 1 8 2 0 1 5 1 1 : 0 7 : 0 6 GMT - 0 7 0 0 ( Pacific Daylight Tirne )

, -
UTC (GMT-0 700), ( Pac i fi c Dayl i ght T ime).
JavaScript Date
- ( !), Unix.
JavaScript ,
( ) .
, valueOf ( ) .
const d = new Date ( ) ;
console . log ( d ) ; / / TZ
console . log ( d . valueOf ( ) ) ; / / Un ix

Da te
Date . (
), Da te, .
, JavaScript ,
() . .
1 1
new Date ( ) ; / /

254 1 5.
1 1 , Ja vaScript
11 : O=Jan , l=Feb . .
new Date ( 2 0 1 5 , 0 ) ; 1 1 1 2 : 00 . . , Jan 1 , 2015
new Date ( 2 0 1 5 , 1 ) ; 1 1 1 2 : 00 . . , Feb 1 , 2 0 1 5
new Date ( 2 0 1 5 , 1 , 1 4 ) ; 1 1 12 : 00 . . , Feb 1 4 , 2015
new Date ( 2 0 1 5 , 1 , 1 4 , 1 3 ) ; 1 1 3 : 00 . . , Feb 1 4 , 2015
new Date ( 2 0 1 5 , 1 , 1 4 , 1 3 , 3 0 ) ; 1 1 3 : 30 . . , Feb 1 4 , 2 0 1 5
new Date ( 2 0 1 5 , 1 , 1 4 , 1 3 , 3 0 , 5 ) ; 1 1 3 : 30 : 05 . . , Feb 1 4 , 2015
new Date ( 2 0 1 5 , 1 , 1 4 , 1 3 , 3 0 , 5 , 5 0 0 ) ; 1 1 3 : 30 : 05 . 5 . . , Feb 1 4 , 2015

1 1 Un ix
new Date ( O ) ; / / 1 2 : 00 . . , Jan 1 , 1 9 70
new Date ( 1 0 0 0 ) ; 1 1 1 2 : 00 : 01 . . , Jan 1 , 1 9 70
new Date ( 1 4 6 3 4 4 3 2 0 0 0 0 0 ) ; / / 5 : 00 . . , 1 6, 201 6

1 1 Unix
new Date ( - 3 65 * 2 4 * 60 * 6 0 * 1 0 0 0 ) ; / / 1 2 : 00 . . , Jan 1 , 1 969

/ / ( - )
new Date ( ' June 1 4 , 1 9 03 ' ) ; / / 1 2 : 00 . . , Jun 1 4 , 1 903 local time
new Date ( ' June 1 4 , 1 9 0 3 GMT- 0 0 0 0 ' ) ; / / 1 2 : 00 . . , Jun 1 4 , 1 903

, , ,
, . UTC (,
, !), , UTC,
.
JavaScript Date: ,
. UTC
(
). JavaScript
"': , ,
, .
( JavaScript
Node) .

Momen t . j s
JavaScript, ,
- ,
Moment . j s.
Moment . j s :
.
( ),
.

Moment.js 255
. ,
http : / /momentj s . .
- ,
Moment . j s CDN, .
<script s rc=" / / cdnj s . cloudflare . com / a j a x / l i b s /moment- t ime zone / 0 . 4 . 0 /
moment-t ime zone . min . j s " > < / s cript>

Node, Moment . j s,
npm insta l l --save moment-timezone,
require.
const moment = require ( ' moment - t ime z one ' ) ;

Moment . j s ,
, .
.

JavaScript
, Moment . j s,
.
, Date,
. , ,
MDN, Date.
,
, - ,
, , Date Moment . j s,
.


Date
JavaScript, . ,
,
, , .
: (
), ,
( ), .


, UTC,
.

256 1 5.
()
. ,
. UTC, ,
UTC Date.
const d = new Date ( Da t e . UTC ( 2 0 1 6 , 4 , 2 7 ) ) ; / / 2 7 , 201 6

Date . UTC ,
Date, Date
.
Date .


( ),
moment . tz Date
.
/ / Momen t . js ,
/ / Da te Ja vaScrip t ,
/ / (O=Jan , l=Feb . . ) . toDa te ()
/ / Da t e JavaScript .
const d =moment . t z ( [ 2 0 1 6 , 3 , 2 7 , 9 , 1 9 ] , ' America /Los_Angele s ' ) . t oDate ( ) ;


, JavaScript .
, ,
.
, ,
Moment . j s ,
.


,
.
, . ,
Date JavaScript
UTC Unix, Date .
"" ,
?
JavaScript - JSON (JavaScript Object Notation).
,
, JSON.

257
const before = { d : new Date ( ) } ;
before . d instanceof date 1 1 true
const j son = JSON . s tringify ( be fore ) ;
const after = JSON . parse ( j son) ;
after . d instdanceof date 11 false
typeo f after . d / / "s tring"

, , JSON
JavaScript. ,
, JavaScript, ,
"" .
after . d = new Date ( after . d ) ;
a fter . d instanceof date /! true

,
, JSON UTC,
JSON Date,
.

.
const before = { d : new Date ( ) . va lueOf ( ) } ;
t ypeof be fore . d 1 1 "numer "
const j son = JSON . stringi f y ( be fore ) ;
const after = JSON . parse ( j son) ;
typeof a fter . d / / " r "
const d = new Date ( a fter . d ) ;

JavaScript JSON
, JSON .
JSON .NET, , JSON
. , -
JSON , ,
. ,
, ,
Unix.
:
, .



. JavaScript Date
, ,

258 1 5 .
. ,
Moment . j s ,
, .
format Moment . j s.
,
. , " " .
Da te
Moment . j s .
const d = new Date { Dat e . UTC { 1 93 0 , 4 , 1 0 ) ) ;

1 1 -

d . toLocaleDateString { ) 1 1 "5/9/1 930 "


d . toLocaleFormat { ) 1 1 "5/9/1 930 4 : 00 : 00 "
d . toLocaleTimeString { ) 11 "4 : 00 : 00 "
d . toTimeString { ) 1 1 "1 7 : 00 : 00 G-0 700 (Pacific Daylight Time) "
d . toUTCString { ) 1 1 "Sa t , 1 0 1 93 0 , 00 : 00 : 00 G"

11
moment { d) . format { 11 --DD ) ; 1 1 "1 930 - 0 5 - 0 9 "
moment { d ) . format { 11 YYYY--DD HH : mm" ) ; 1 1 " 1 930-05-09 1 7: 00
moment { d ) . format { "YYYY--DD HH : mm Z 11 ) ; 1 1 "1 930-05-09 1 7 : 00 -0 7 : 00
moment { d ) . format { "YYYY--DD HH : mm [ UTC ] Z 11 ) ; 1 1 " 1 930-05-09 1 7 : 00 - 0 7 : 00

moment { d ) . format { " dddd, [ the ] Do , 11 ) ; 1 1 "Friday, the 9th, 1 930 "

moment { d ) . format { "h : mm " ) ; 1 1 "5 : 00 "

,
. JavaScript ,

, .
, , ,
.

Moment . j s; . , ,
, Moment . j s
. , -
. , , .. "" 1, 2, 3 ... ;
"S " - 01, 02, 0 3 . .. ; " " - Jan, Feb, Mar . . . ; " " - January, February, March... .
" " : "Do" lst, 2nd, rd
.. ,
, : " [] " Ml, 2 ..

259
, Moment . j s
, - ,
EST PST. z
.
-
Moment . j s.



Date, .
const d = new Date ( Date . UTC ( 1 8 1 5 , 9 , 1 0 ) ) ;

/ / -
d . getFullYear ( ) / / 1 81 5
d . getMonth ( ) / / 9 - October
d . getDate ( ) // 9
d . getDay ( ) / / 1 - Monday
d . getHours ( ) // 17
d . getMinute s ( ) //
d . getSeconds ( ) //
d . getMi l l i seconds ( ) / /

// :
d . getUTCFullYear ( ) / / 1815
d . getUTCMonth ( ) // 9 October-

d . getUTCDate ( ) / / 10
11 . . ..
.

Moment . j s ,
, , .


(
?) JavaScript.
, Date ,
.
const dl new Date ( 1 9 9 6 , 2 , 1 ) ;
const d2 new Date ( 2 0 0 9 , 4 , 2 7 ) ;

dl > d2 / / false
dl < d2 // true

260 1 5 .

- ,
.
const msDiff d2 - dl ;
= / / 4 1 7 740400000
const daysDiff = msDi f f / 1 0 0 0 / 60 / 6 0/ 2 4 ; / / 4834 . 9 6

Arra y .
prototype . sort.
const dates = [ ) ;
/ /
const min = new Date ( 2 0 1 7 , , 1 ) . va lueOf ( ) ;
const delta = new Date ( 2 0 2 0 , , 1 ) . va l ueOf ( ) - min;
for ( le t i = O ; i < l O ; i++ )
date s . push ( new Date ( min + delta *Math . random ( ) ) ) ;
/ / ()
/ / ( ) :
dates . sort ( ( , ) => - ) ;
1 1 :
dates . sort ( ( , ) => - ) ;

Moment . j s
, .
const m = moment ( ) ; 1 1
m . add ( , ' da ys ' ) ; 1 1
m . sut ract ( 2 , ' years ' ) ; 1 1

m = moment ( ) ; 1 1
m . startOf ( ' year ' ) ; 1 1 1
m . endOf ( ' month ' ) ; 1 1 31

Moment . j s .
const m = moment ( )
. add ( l O , ' hours ' )
. sutract ( , ' days ' )
. endOf ( ' month ' ) ;

/ / - , ,
1 1 1 0 , 3



: , " ': Moment . j s
.

261
moment () . subtract ( l O , ' seconds ' ) . fromNow ( ) ; 1 1
moment () . subtract ( 4 4 , ' seconds ' ) . fromNow ( ) ; 1 1
moment () . subtract ( 4 5 , ' seconds ' ) . fromNow ( ) ; 1 1
moment () . subtract ( S , ' minute s ' ) . fromNOw ( ) ; 1 1 5
moment () . subtract ( 4 4 , ' minute s ' ) . fromNOw ( ) ; 1 1 4 4
moment () . subtract ( 45 , ' minutes ' ) . fromNOw ( ) ; 1 1
moment () . subtract ( S , ' hours ' ) . fromNOw ( ) ; 1 1 4
moment () . subtract ( 2 1 , ' hours ' ) . fromNOw ( ) ; 1 1 21
moment () . subtract ( 2 2 , ' hours ' ) . fromNOw ( ) ; 1 1
moment () . subtract ( 3 4 4 , ' da ys ' ) . fromNOw ( ) ; 1 1 3 4 4
moment () . subtract ( 3 4 5 , ' days ' ) . fromNOw ( ) ; 1 1

, Mornent . j s ( )
.
.


.
Unix
( 1 1 970 UTC).
, .
, Mornent . j s.

.
, .
Mornent . j s Mozilla Developer Network.

262 1 5.
1 6

Math

JavaScript Math,
, (
, , ,
).
, , JavaScript
. , -
; 64-
IEEE 754.
: .
,
JavaScript . ,
JavaScript .
, , ,
th . j s .
, .
.
, ,
( ) .
th , .
, ,
th , .


, ..
2 . 0 0 9 3, 2 . 1 1 9 4 9 0 3 2
1 , 9 4 9 , 032.1

1 ,
, , , , .
JavaScript
,
, .
, ,
, .
JavaScript , .
, (
).
;
,
.



, Nner . prototype . t oFixed.
const = 1 9 . 5 1 ;
x . toFixed ( ) ; 1 1 "1 9 . 51 0 "
x . toFixed ( 2 ) ; 1 1 " 1 9 . 51 "
. toFixed ( 1 ) ; 1 1 "19. 5"
x . toFixed ( O ) ; 1 1 "20 "

, :
.


,
Nne r . prototype . toExponential.
const = 3 8 0 0 . 5 ;
x . toExponentia l ( 4 ) ; 1 1 "3 . 8005+ 4 " ;
x . toExponentia l ( ) ; 1 1 "3 . 80 1 + 4 " ;
x . toExponentia l ( 2 ) ; 1 1 "3 . 80+4 ";
x . toExponent ial ( l ) ; 1 1 "3 . 8+4 ":
x . toExponent ial ( O ) ; 1 1 "4+ 4 ";

Nne r . prototype . toFixed, , .


- .



, Nner . prototype . toPrecis ion.

264 1 6 . Math
let = 1 0 0 0 ;
x . toPrecis ion ( 5 ) ; 11 "1000 . "
x . t o Precis ion ( 4 ) ; /! "1000 "
x . t o Precis ion ( 3 ) ; 1 1 "1 . 00+3 "
x . t o Precis ion ( 2 ) ; 1 1 "1 . +3 "
x . toPre c i s ion ( l ) ; 1 1 "l e + 3 "
= 1 5 . 335;
x . toPre c i s ion ( ) ; 1 1 "1 5 . 335 0 "
x . toPreci s ion ( 5 ) ; 1 1 "1 5 . 335 "
x . t o Pre c i s ion ( 4 ) ; 1 1 "1 5 . 34 "
x . toPrec i s ion ( 3 ) ; 1 1 "1 5 . 3 "
x . toPrec i s ion ( 2 ) ; 1 1 "1 5 "
x . t o Precision ( l ) ; 1 1 "2e+l "

, .
.


(, -
), Numer . prototype . toString,
, ( 2-36).
const = 1 2 ;
x . toString ( ) ; 1 1 "1 2 " ( 1 0)
x . toString ( l O ) ; 11 "1 2 " ( 1 0)
x . toStr ing ( l ) ; 11 " " ( )
x . toString ( 8 ) ; / / "1 4 " ()
x . toString ( 2 ) ; 1 1 "1 1 00 " ()


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

. ,
Nurneral . j s,
.

Math.
//
Mat h . E / / : -2 . 71 8
Math . PI / / : -3 . 1 42

/ / ;
/ /
Mat h . LN2 / / 2 : -0 . 693
Math . LN l O / / 1 0 : - 2 . 303
Math . LOG2E / / 2 Ma th . E : -1 . 433
Math . LOG l OE / / 1 0 Ma th . E: 0 . 434

//
Mat h . SQRT1 _2 / / 1 /2 : . 70 7
Mat h . SQRT2 / / 2 : -1 . 4 1 4



- th . pow,
, ,
. 1 6. 1 .
1 6.1 .

Math . pow ( , ) xr Math . pow ( 2 , 3 ) 11 8
Math . pow ( l . 7 , 2 . 3 ) 11 . 39
Math . s qrt ( x ) Mat h . s qrt ( 1 6 ) 11 4
R. Math . sqrt ( 1 5 . 5 ) 11 . 94
Math . pow ( , . 5 )
Math . cbrt ( x ) . Math . cbrt ( 2 7 ) 11 3
Math . pow Math . cbrt ( 2 2 ) 11 -2 . 8
(, 1 / 3 )
Math . exp ( x ) <!'. Math . exp ( l ) 11 -2 . 7 1 8
Math . pow ( Math . E , ) Math . exp ( 5 . 5 ) 11 -24 4 . 7

266 16. Math


. 1 6. 1


Math . expml ( x ) "-1 . Math . expml ( l ) 11 -1 . 718
th . ( ) - 1 Math . expm1 ( 5 . 5 ) 11 -2 4 3 . 7
Math . hypot Math . hypot ( , 4 ) 11 5
( xl , 2 , . . . ) : Math . hypot ( 2 , , 4) 11 -5 . 3 6

12 + / + ...


Mat h . l o g .
-

"log" " 1 0': "ln" - "


': , JavaScript "log" " ':
S Math . loglO.
1 6.2. r

Math . log ( x ) Math . log (Math . E ) 11 1
Math . log ( 1 7 . 5 ) 11 -2 . 8 6
Math . loglO ( x ) 1 . Math . log10 ( 1 0 ) 11 1
th . log ( ) / Math . log1 0 ( 1 6 . 7 ) 1 1 -1 . 22
Math . log ( 1 0 )
Math . log2 ( x ) 2 . Math . log2 ( 2 ) 11 1
th . lg ( ) / Math . log2 ( 5 ) 1 1 -2 . 32
Math . log ( 2 )
Math . loglp ( x ) 1 + . Math . loglp (Math . E - 1 ) 11 1
th . 1 og ( 1 + ) ath . l oolf ( 1 7 . 5 ) 11 -2 . 92


. 1 6.3 ,
, ,
, ,
.
1 6.3. r r

Math . abs ( x ) Math . abs ( - 5 . 5 ) 11 5.5
Math . abs ( 5 . 5 ) 11 5.5
Math . s ign ( x ) : - Math . s ign ( - 1 0 . 5 ) // -1
, -1; Math . s ign ( . 7 7 ) // 1
- , 1;
- ,

r 267
. 16.


Math . ceil ( x ) , Math . ceil ( 2 . 2 ) 11 3
Math . cei l ( -3 . 8 ) 11 -3
Math . floor ( ) , Math . floor ( 2 . 8 ) 11 2
Math . floor ( -3 . 2 ) 11 -4
Math . trunc ( x ) ( - Math . trunc ( 7 . 7 ) 11 7
) Math . trunc ( -5 . 8 ) 11 -5
Math . round ( x ) - Math . round ( 7 . 2 ) 11 7
Math . round ( 7 . 7 ) 11
Math . round ( -7 . 7 ) 11 -
Math . round ( -7 . 2 ) 11 -7
Math . min Math . min ( l , 2 ) 11 1
( x l , 2 , . . . ) Math . min ( 3 , 0 . 5 , . 66) 11 0. 5
Math . min ( 3 , 0 . 5 , -0 . 66 11 - 0 . 66
Math . max - Math . max ( l , 2 ) 11 2
( x l , 2 , . . . ) Math . max ( 3 , . 5 , . 66) 11 3
th . max ( - 3 , . 5 , -0 . 6 6 ) 11 0. 5


Math . random.
, 1 . ,
, ,
() ().
Math . random [, 1 ).
th . r andom
.
. 1 6.4.
, m n .
-

1 6.4.

[, 1 ) Math . random ( )
[, ) + ( y-x) *Mat h . random ( )
[m, n) m + Math . floor ( ( n-m) *Math . random ( ) )
[m, n] m + Math . floor ( ( n-m+l ) *Math . random ( ) )

JavaScript
,
, .
, seedrandom.
j s (David Bau).

268 1 . Math
( Pseudorandom Number
Generator - PRNG) ( )
" " (Random Number Generator - RNG).
PRNG , -
,
- .

r
. , ,
, . 1 6.5.
th , .
n 1 6.S.

Math . sin ( x ) Math . sin (Math . PI / 2 ) 11 1
Math . sin (Math . PI / 4 ) 1 1 - . 707
Math . cos ( x ) Math . cos (Math . PI ) 11 -1
Math . cos (Math . PI / 4 ) 1 1 - . 707
Math . tan ( x ) Math . tan (Math . PI / 4 ) 1 1 -1
Math . tan ( O ) 11
Math . asin ( x ) () Math . as in ( O ) 11
( ) Math . asin (Math . SQRTl 2 )
- 1 1 - . 785
Math . acos ( x ) () Math . acos ( O ) 1 / - 1 . 5 7+
( ) Math . acos (Math . SQRT1_2 ) 1 1 - . 785+
Math . atan ( x ) () Math . atan ( O ) 11
( ) Math . atan (Math . SQRT1_2 ) 1 1 - 0 . 61 5
Math . atan2 ( ) Math . atan2 ( 0 , 1 ) 11
(, ) ( , ) , Math . atan2 ( 1 , 1 ) 1 1 - . 785

,
. : 180 7t.
.
function deg2rad ( d ) return d / 1 B O *Mat h . P I ;
funct ion rad2deg ( r ) { return r /Math . PI * l B O ; }


, , ,
. 1 6.6.

269
1 6..

Math . s inh ( x ) Math . s inh ( O ) 11
Math . s inh ( l ) 11 -1 . 1 8
Math . cosh ( x ) Math . cosh ( O ) 11 1
Math . cosh ( l ) 11 -1 . 54
Math . tanh ( x ) Math . tanh ( O ) 11
Math . tanh ( l ) 11 - . 7 62
Math . as inh ( x ) Math . as inh ( O ) 11
() Math . as inh ( l ) 11 - 0 . 881
Math . acosh ( x ) - Math . acosh ( O ) 11 NaN
() Math . acosh ( l ) 11
Math . atanh ( x ) - Math . atanh ( O ) 11
() Math . atanh ( O ) 11 - 0 . 615

270 1 . Math
1 7

(regular expression)
. ,
, URL, ,
.
,
. , ,
, , .

, " , ".

.
- (
?).
.
" " (regular expression)
"regex" "regexp"; .


-
, , .
. ,
,
String .
prototype. .
, , - ,
, St ring . prototype.
const input = "As I was going to Saint Ive s " ;
input . startsWith ( "As " ) / / true
input . endsWith ( " Ive s " ) / / true
input . st artsWith ( " going " , 9 ) 1 1 true 9 -
input . endsWith ( " going " , 1 4 ) 1 1 true 1 4 -
input . includes ( " going " ) 1 1 true
input . includes ( " going " , 1 0 ) 1 1 fa l s e - - 1 0-
input . indexOf ( " go i ng " ) 11 9
input . indexOf ( "going " , 1 0 ) 1 1 -1
input . indexOf ( " " ) 1 1 -1

, . ,
input . start sWi th ( " as " ) false.
, .
input . toLowerCa se ( ) . st artsWith ( " a s " ) // true

, ; S t r ing . prototype .
toLowe rCas e ( ,
JavaScipt !).
, , ,
String . prototype . repl ace.
const input = "As I was going t o Saint Ive s " ;
const output = input . replace ( " going " , "walking" ) ;

(input )
; output , " going"
"wal king " ( input,
).

r
,
, JavaScript.
, , .
, , .
JavaScript RegExp.
, RegExp,
, .
.
const rel / going / ; / / ,
1 1 "going"
const re2 new RegExp ( " going " } ; / /

RegExp ,
, , ,
.

272 1 7 .
n rn

.
,
(
). / \ w { 3 , } / i g,
(
). ; .
.
const input = "As I was going to Saint Ives " ;
const re = / \w { , } / i g ;

/ / (input)
input . rnatch ( re ) ; // [ "was " , "going " , "Sain t ", "Ives "}
input . search ( re ) ; // 5 ( 5)

// (re)
re . t e s t ( input ) ; / / true (inpu t
/ / )
re . exec ( input ) ; / / [ "was "} ( )
re . exec ( input ) ; / / [ "going " J ( " " , )
re . exec ( input ) ; 1 1 [ "Sain t "J
re . exec ( input ) ; 1 1 [ "Ives " }
re . exec ( input ) ; / / n u l l - -

/ / ,
1 1
input . rnatch ( / \w { , } / i g ) ;
input . search ( / \w { , } / ig ) ;
/ \ w { , } / i g . t e s t ( input ) ;
/ \w { , } / i g . exec ( input ) ;
11

RegExp . prototype .
, - .
S tr ing . prototype . match RegExp . prototype . test.

n rn
String . prototype . replace
.
! - ,
4- .

273
const input = "As I was going to Saint Ives " ;
const output = input . replace ( / \w { 4 , } / ig , ' * * * * ' ) ; 1 1 "As I was * * * *
11 to **** **** "


"
" ( "
"), , .

.

.
.
,
,
. ;
.
J N 1 I N U R J 1 N

.
LION, NATURE EEL ( I ON, ). ,
, .
. , ,
, .
, ,
LION, ION, NATURE EEL. ,
, .

. ,
-

" ':
, , J. .
.
(consumed).
, L.
', LION!"
, L.
. , I, , N.
. ! ,
, , L, I , N
. . LION NATURE

274 1 7.
. .
, ,
. , "" ,
. ,
NATURE, N . ,
, - ATURE, .
EEL.
LION . ?
L,
LION, L. I,
. ,
: , LIX.
, , ,
( L ),
.
NATURE, N LION.
. 1 7. 1 .

J N L I N U R J L N
+ ? ".

J N L I N U R J L N
+ ? ". J

' ' f'

A N L I O N A T U R E J X E E L N P
+ ? ".

N L I N U R J L N
+ ? . . . N
L I N U R J L N
+ ? ! L
L I N U R J L N
+ ? ! r

,, L I N U R J L N
+ ? !
L I N U R J L N
+ ! ( LION)
U R J L N
+ ? ".

" ..t, 1 11

. 1 7. 1 .

275

, ""
.
.
.

.
,
;
( , ).

, ,
. , ,
, .

, ; ,
, ,
, .

, L-, ,
, ( <>,
< area>, < l ink>, <script>, <source>, <meta> ) . ,
( <Area>, <LINKS> ..).

(alternation).
const html = ' HTML with < href= " /one " >one link</a>, and some JavaScript . ' +
' < script src= " stuff . j s " > < / script> ' ;
const mat ches = html . match ( /area J a l l in k l script l source / i g ) ; / /

( J ) , -
. ig ( i )
(g). g .
: " area, , l ink, script source,
". "
area ?" ,
. ,
a rea, .
, rea .

276 1 7.
, area, ;
area !
, ,
: link <>,
, L-,
.
/<a rea 1 < 1 <l ink 1 <script 1 <source/ (
,
), .

n L-

: HTML-.
, , , ,
, L-,
. (parsing)
- .
(regular) (
!). ,

. ,
? ,
.
L-,
,
. , 1 00% ,
(parser). .
const html ' <br> [ ! CDATA [ [ <br> ] ] ' ;
=

const mat ches html . ma t ch ( /<br > / ig ) ;


=

;
<br>; -
(character data CDATA), L-.
-

,
(, <>,
<> ).
, :
- (,
L-), ,
.

L- 277

(character set)
.
,
. , ,
.
const beer99 = " 9 9 b o t t l e s of beer on the wall " +
" t a ke 1 down and p a s s i t around -- " +
" 9 8 b o t t l e s o f beer on the wall . " ;
const matches = beer 9 9 . match ( / 0 J 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9/ g ) ;

! , ?
? , , ?
.
. ,
. .
const ml beer9 9 . ma t ch ( / [ 0 12 3 4 5 67 8 9 ] /g ) ; / /
const m2 = beer9 9 . ma t ch ( / [ 0 - 9 ] / g ) ; / / !

. ,
(
, ).
const match = beer99 . ma t ch ( / [ \ - 0- 9 a - z . ] / i g ) ;

, :
/ [ . a-z0 - 9 \ - ] /. "-"
; JavaScript
(
).
-
. : "
, ".
( ) .

const match = beer9 9 . ma t ch ( / [ \ -0 - 9 a - z . ] / ) ;


(
, , ).

278 1 7.

( ),
.



\d (0-9]
\D (Q-9]
\s ( \t \v\n \ r ] ,

\S [ \ t \v\n\ r ]
\w [ a- zA-Z ] ,
,
CSS
\W

, , -
( \s). , ,
, , ,
.

const s tuff =

' hight : 9\n' +


' medium : 5\n' +

' l ow : 2\n' ;
const l evels s tu f f . ma t ch ( / : \ s * [ 0 - 9 ) / g ) ;

( * \s " '; .)
( \ D, \S \W);
. ,

.
: , , .
, ,
( ,
). \D ( ..
) .

const me s s yPhone = ' ( 5 0 5 ) 555-1515 ' ;


const neat Phone = me s s yPhone . replace ( / \ D / g , ' ') ;

279
\ S ,
- (
, !).
const field ' s omething ' ;
const valid = / \ S / . t e s t ( field) ;


(repetition)
. ,
. (
)?
, , .
const match = beer9 9 . match ( / [ 0 - 9 ] [ 0 - 9 ] [ 0 - 9 ] 1 [ 0- 9 ] [ 0- 9 ] 1 [ 0 - 9 ] / ) ;

,
( ) , (
). -, -
, , ,
. , .
const match = beer 9 9 . match ( / [ 0- 9 ] + / ) ;

+ : ,
. "
" . -
(modifier), , .
!
.

{n} n / d { 5 } / (
, )
{ n, } n / \ d { 5 , } /

{ n, rn } n, / \d { 2 , 5 } / ,
rn ,
? . / [ a- z J \d? / i
{ , 1 } , ( !)

280 1 7.
-

* / [ a- z ] \d* /i -
( , ( !)
" ")
+ / [ a- z ] \d+ / i
,

" "
- ,
" -" ( ).

.
, ,
.
const input = "Address : 3 3 3 Main S t . , Anywhere, NY, 5 5 5 32 . Phone : 555-555-2525 . " ;
const match = input . match ( / \d { 5 } . * / ) ;

,
, , I-.
,
, , .
, .. .
const equat ion = " ( 2 + 3 . 5 ) * 7 " ;
const match = equation . match ( / \ ( \d \ + \d\ . \d\ ) \ * \d/ ) ;


. , * txt
.

" ': * - "':


, . ,
* ,

.
* ,
,
, .

" " 281


,
,
, ,
? ( , !)
, , , [ \ s \ S] . -

... ,
. , !


(
, !). (grouping)
(subexpression), , .
, "
" , .
, " " (noncapturing
group), .
, ,
.
,
, .
,
( ? : <>) , <> ,
-

. . ,
. , org . edu. .

con s t text = "Vi s i t ore i l l y . com today ! " ;


const match = t ext . match ( / ( a - z ] + ( ? : \ . com l \ . org J \ . edu ) / i ) ;

,
. ,
.
. . URL,
http : / /, https : / / / / (URL,
), ( ? ) .
const html = ' <link rel=" styleshee t " href=" http : / / insecure . com/ stuf f . cs s " > \ n ' +
' <link rel=" s tylesheet " href=" https : / / s e cure . com/ securestuf f . c s s " >\n ' +
' <l in k rel=" stylesheet " href= " / / anything . com/ flexi e . cs s " > ' ;

const matches = html . match ( / ( ? : ht t p s ? ) ? \ / \ / [ a - z ] [ a - z 0 - 9- ] + [ a - z 0 - 9 ] + / ig ) ;

282 1 7 .
, , ? .
,
. : ( ? : https ? ) ?.
" ': , "s
". , ,
(.. ).
, . ,
( http?), http
https. ( ,
: \ / \ /). .
, ,
(
).
. , URL / / gotcha
() , , / /va l i d . .
URL - ,
.

("
URL"), ,
!
- .
URL ( URL),
, URL
..
, .
, ,
, . ,
,
.

"':


-
.
(greedy), ..
. .

283
L-, , , < i >
<strong>. .
const input = "Regex pros know the difference between\n" +
" < i>greedy< / i > and < i > l a zy< / i > matching . " ;
input . replace ( /<i> ( . * ) < \ / i> / i g , ' < strong> $ 1 < / strong> ' ) ;

$ 1 ( . * )
( - ).
. .
"Regex pros know the d i f ference be tween
< s t rong>greedy< / i > and < i > l a z y < / s t rong> matching . "

, ,
: ,
, .
: <i>, " ,
< / i >. < / i >,
, .
,
,
( * ).
.
input . replace ( /<i> ( . * ? ) < \ / i > / i g , ' <strong> $ 1 </ strong> ' ) ;

- ,
*. : "
, < / i : ,
, < / i >,
. (lazy)
, - , .
( * , +, ?, { n } , { n , } { n , m} )
, (
* + ) .


-
(backreference).
, , .
, .
, -
( , -,

284 17.
). , PJJP, GOOG
. . (
) , ,
1 . ,
, . , \ 1
" ". ? .
const promo " Opening for is the dynamic GOOG ! At the o f fice now ! " ;
const bands = promo . ma t ch ( / ( ? : [ A-Z ] ) ( ? : [ A-Z ) ) \2 \ 1 /g ) ;

, , , \ 2 \ 1 . ,
, \2
\ 1 .
, , .
, , (
), - .
HTML
. .
/ ! ,
/ / :
const html = ' <img a l t = ' A " simple " example . ' > ' +
' <img a l t = " Don ' t abuse i t ! " > ' ;
const matches = html . match ( /< img alt= ( ? : [ ' " ] ) . * ? \ l / g ) ;

, :
alt , .
, al t .
.
,
, (
, ), \ 1 -

.. .
.
*, . .
? , ?
, , ,
.


, ,
. L-, ,

285
<> URL,
href.
l e t html = ' < class="nope " hre f= " / yep" >Yep< / a> ' ;
html = html . replace ( /<a . * ? ( href=" . * ? " ) . * ? > / , ' < $ 1 > ' ) ;

, 1 .
\ 1 ;
$ 1 .
,
<>. ,
hre f .
. class href .
let html = ' < c l a s s = " yep" href= " / yep" id= " nope " >Yep</a> ' ;
html = html . replace ( /<a . * ? ( cl a s s= " . * ? " ) . * ? ( href=" . * ? " ) . * ? > / , ' < $ 2 $ 1 > ' ) ;

:
class href , href.
, class href
( ), ,
, .
.
$ 1, $ 2 , $ ' ( ), $ &
( ) $ ' ( ).
, $ $ .
const input = " One two three " ;
input . replace ( /two / , ' ( $ ' ) ' ) ; // " ( ) three "
input . replace ( / \w+/g , ' ( $ & ) ' ) ; // " (One) (two) (three) "
input . replace ( /two / , " ( $ ' ) " ) ; 11 " ( three) thre e "
input . replace ( /t wo / , " ( $ $ ) " ) ; 11 " ( $ ) three "

,
, !


,
.
L
. , ,
<> : c l a s s , i d
href, . ,
. , ,

286 1 7.
, . ,
( ).
const html =
' < c l a s s= " fo o " href= " /foo" id= " foo" >Foo< /a>\n ' +
' < href= ' / foo ' C l a s s= " foo" >Foo</ a > \ n ' +
' < href= " / foo" >Foo< /a>\n ' +
' < oncl ick= " j avascript : alert ( ' foo ! ' ) " href= " / foo" >Foo< / a> ' ;

,
: !
,
: - <> -
<> , .
. , , -
<>, , c l a s s , id href, ,
. , ,
, ,
. ,
String . prototype . spli t, .
function sani t i z eATag ( aTag) {
1 1 . . .
const parts = aTag . match ( /< a \ s + ( . * ? ) > ( . * ? ) < \ /a > / i ) ;
/ / parts [ 1 ] - <>
1 1 parts [2] - , <> </ >
const attribut e s = parts [ l ]
1 1
. sp l i t ( / \s+ / ) ;
return ' < ' + attributes
11 cla s s , id href
. fi l t e r ( at t r => / ( ? : cl a s s l id l hr e f ) [ \ s=] / i . t e s t ( at t r ) )
1 1
. j oin ( ' ' )
/ / <>
+ '>'
/ /
+ parts [ 2 ]
1 1
+ ' < / > ' ;

, , .
,
: - <>, -
(

287
) - .
.
: saniti zeATag HTML,
, L-, <>.

<>.
html . ma t ch ( /< a . * ? > ( . * ? ) < \ / a > / ig ) ;

? S tr ing . prototype .
replace .
.
. ,
console . log, , .
html . replace ( /<a . * ? > ( . * ? ) < \ / a > / i g , funct ion (m, g l , o f f s e t )
nsl . lg ( ' < > $ { of f s et } . :
$ { gl } 1 ) ;
});

, S tring . prototype . replace,


.
( $&).
( ). ,
.
(), .
( ).


. ,
. ,
undefined,
. , ;
.
.
<> <> HTML,
.
html . replace ( /<a . * ? < \ / a> / i g , functi on ( m ) {
return s aniti z eATag (m) ;
});

- ,
sani t i z eATag , String . prototype . replace,

288 1 7.
saniti zeATag
.
html . replace ( /<a . * ? < \ /a > / i g , saniti z eATag ) ;

, . ,
,
, ,
String . prototype . replace!


,
, , .
(anchor). : , $,
,

.
const input " I t was the best of t ime s , i t was the worst o f t ime s " ;
=

const beginning inpu t . match ( / \wt / g ) ;


= 1 1 "It "
const end input . match ( / \w+ $ /g ) ;
= 1 1 " times "
const everything input . match ( / . * $ /g ) ; 1 1 ,
=

const nomatchl input . match ( / be s t / ig ) ;


const nomatch2 inpu t . match ( /wor s t $ / ig ) ;
=

, .
, .
(
), m (multiline).
const input "One l i n e \ nTwo l i ne s \nThree l ines \nFour " ;
=

const beginnings input . match ( / \w+/mg ) ; / / [ "One ", " Two ", " Thre e " , "Four "J
=

const endings = inpu t . match ( / \w+ $ /mg ) ; // [ "lin e " , "lines " , "lines " , "Four"J

n
, ,
. ,
\ \ t.
, .
, \w
\W ( ) .
,
( ,
). ,
.

289
const inputs = [
" j ohn@doe . co" , //
" j ohn@doe . co is ea i l " , 11
" ea i l i s j ohn@doe . co" , 11
" u s e j ohn@doe . co, ea il " , 11
" eai l : j ohn@doe . co . " , ! /
];

,
. , ,
, "
" .
const ea i lMatcher =
/ \ [ - z ] [ a - z 0 - 9 . _- ] * @ [ a - z ] [ a - z 0 - 9_- ] + \ . [ a - z ] + ( ? : \ . [ a - z ] + ) ? \ / i g ;
input s . ( s => s . replace ( ea i lMatcher , ' < hre f=" a i l to : $ & " >$ &< / > ' ) ) ;
/ / [
// "< href= "a i l t o : j ohn@doe . co">j ohn @doe. </ > " ,
// "< href= "a i l t o : j ohn @doe . co">j ohn @doe. </ > is ema i l " ,
// " ea i l i s < href="a i l to : j ohn@do e . co ">john@doe. co</a> " ,
// "use < href="a i l t o : j ohn@doe . co ">j ohn@doe . co</a> , ea i l " ,
// " ea i l : <a href="a i l t o : j ohn @doe. com>j ohn @doe. co</a > . " ,
11 }

,
, . ,
, ,
(
, , $ &, ,
... ).
, ,

. , / \bcount/ count countdown, discount, recount
accountale; / \bcount \ B / countdown; / \Bcount \ discount
recount, / \Bcount \/ t.


, (lookahead) .
( )
. , :
, .
, , (match),
"" .

290 1 7.
, .
, ;
.
-
. , ,
,
. , .
function va l idPa s sword ( p ) {
return / [A- Z ] / . te s t ( p ) & & //
/ [ 0 - 9 ) / . te s t ( p ) & & 11
/ [ a - z ] / . te s t ( p ) & & 11
! / [ a - zA- Z 0 - 9 ) / . test ( p ) ; 11

.
.
funct ion val idPassword ( p ) {
return / [A- Z ] . * [ 0- 9 ) [ a - z ] / . t e s t ( ) ;

,
,
. ,
.
. , -
, .
JavaScript ( ?=<> ) . "
" (negative lookahead): ( ? ! <> ) ,
, .
.
function validPa s sword ( p ) {
return / ( ?= . * [A- Z ] ) ( ?= . * [ 0 - 9 ] ) ( ?= . * [ a- z ] ) ( ? ! . * [ a - zA- Z 0 - 9 ) ) / . t e s t ( ) ;

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

291

,
RegExp.
, ,
,
JavaScript. RegExp ,
. ,
, ; -
.
RegExp,
, . .
const users = [ "mary " , " n i c k " , " arthur " , " sam" , " yvette " ] ;
const text = "User @ arthur s t arted the backup and 1 5 : 1 5 , " +
" and @ n i c k and @ yvette restored it at 1 8 : 3 5 . " ;
const userRegex = new RegExp ( ' @ ( ? : $ { users . j o in ( ' i ' ) } ) \ \b ' , 'g' ) ;
text . match ( userRegex ) ; / / [ "@a r thur " , "@n i ck ", "@yvet t e " ]


: / @ ( ? : mary 1 nick 1 arthur 1 sam l yvette ) \/g,
. (
); .


,
.
20% 80% .
( !)
(, https : / / regex l O l . com/ # j avascript).
, , - ,
;
.

292 1 7.
1 8

JavaScript

JavaScript
. ,
JavaScript . JavaScript ,

API.
JavaScript
. -
,
. .

ESS S?
, , S.
, ,
S -.
, S
( JavaScript). -
HTTP(S) ,
JavaScript, . ,
.
"" ;
( )
-.
, .
,
ESS. :
S .
, .
,
2.
Firefox .
, ,
.


(Document Object Model - DOM) -
L-,
.
DOM - . (node):
( )
(child node). - (document);
, <html>. <html>, ,
: <head> <body>. DOM . 1 8. 1 .

. 18. 1 . DOM

294 1 8. JavaScript
DOM ( )
Node ( Node . j s, ). Node
parentNode chi ldNode s, , nodeNarne
nodeType.

DOM ,
(element) HTML. ,
( <>) L-, ,
, (text node).
, -
, . (
) , L-,
"': " ':


L-. s imple . html.
< ! doctype html>
<html>
<head>
<meta charset="ut f- 8 " >
<title>poca HTML-cpaa < / t itle>
< s t yle>
. callout {
borde r : solid lpx # f fO O B O ;
margin : 2 4;
padding : 2 ;

. code {
background : # ;
margin : l p x 2;
paddi n g : lpx 4 ;
font- famil y : monospace ;

< / style>
< /head>
<body>
<header>
<hl> L-< / h l >
< / header>
<div id= " content " >
<> < i >< / i > L- . < />
<div class=" callout " >
<> ! < />
< /div>
<> ( , <span

295
class="code" >#cont ent < / span> )
(
) . < />
<> ( , <span class="code " > . cal lout< / span> )
. < />
<div i d= " ca l lout2 " c l a s s = " c a l l out fancy " >
<> L- . < />
< /div>
< /div>
< /body>
< / html>

nodeType nodeName ( ).
nodeType - . Node
, .
Node . ELEMENT_NODE (L-) Node . _NODE
( , L-).
node Type MDN
(https : / / deve loper . mo z i l l a . org/ru/docs /We/API /Node /nodeType ) .
,
(traverse) DOM , document.
function printDOM ( node , pref i x ) {
console . log (prefix + node . nodeName ) ;
for ( let i=O ; i<node . childNode s . lengt h ; i + + ) {
printDOM ( node . childNodes [ i ] , pre f i x + ' \t ' ) ;

printDOM ( document , ' ' ) ;


(depth-first, pre-order traversal). , ,
.
, .
, L-
( DOM
) . , DOM
L-.


, API DOM TreeWal ke r,
DOM (
).
document .
createTreeWal ke r MDN.

296 1 8. JavaScript

,
. - (direct) (.. "
"), - (.. "") .
(descendant)
. (ancestor)
, ..

- DOM
DOM - ( get . . . ),
HTML.
- docume n t . g e t E l emen t B y i d. L
- ,
document . getE l ementByid .
document . getE l ementByi d ( ' content ' ) ; / / <div id="con t en t "> . . . </div>


( L- ),

. - ( , -
)
,
.
.

document . g e t E l ementsByClas sName ,


.
const callouts = docurnent . getElementsByClas sName ( ' callout ' ) ;

document . getElementsByTagName ,
.
const paragraphs = docurnent . getElementsByTagName ( ' p ' ) ;

DOM, ,
JavaScript, HTMLCollect ion,
" ': for,
Arra y . prototype (, map, fil ter reduce ) ,
. HTMLCol l ec t i on
, [ . . . d o c ume n t .
getE l ementsByTagName () ] .

297
DOM
getE l ementByid, getElementsByClas sName getElementsByTagName
, ( ) ,
(,
), .
document querySelector que rySe l e ctorAl l
CSS (CSS selector).
CSS ( <>, <di v>
..), , ( )
. ,
( ). ,
<> DOM, br - <br>.
, : . cal lout
cal lout.
, : . c a l l out . fancy
cal lout fancy. ;
, a#cal lout2 . callout . fancy <>
cal l out2 callout fancy (
, ,
() ... !).
CSS -
HTML, ,
que ryS e lectorAl l. , ,
document . querySelectorAll ( ' . callout ' ) .
, que rySe l e ctorAl l
.

, DOM. CSS
DOM.
,
. , # cont ent <>,
, content.
# content di v <>,
<di v>, content.
"" ( > ),
, . ,
#content > <>,
content ( " # c ontent " ) .

298 1 8. JavaScript
, .
, body . content > <>,
content, <body>.
,
.
MDN ( ht tps : / / developer . moz i l l a . org/ru /
doc s /Learn/CS S / Introduction_to_CSS/ Selectors ) .

DOM
, , , ,
" ?" .
, textContent innerHTML,
. textContent
"" L-, inne rHTML
L- ( DOM). ,
.
const paral = document . getElementsByTagName ( ' p ' ) [ ] ;
para l . t extContent ; / / " L- . "
para l . innerHTML; / / " <i></i> L- . "
para l . t extContent = " L- " ; / / ,
para l . innerHTML = " < i>< / i > L- " ; / / !

t extContent inne rHTML


: , -
-
, . ,
-,
innerHTML <body>!

DOM
, DOM,
innerHTML . ,
document . createE l ement. ,
DOM; .
; <div i d= " content " >,
- .
const pl = document . createElement ( ' p ' ) ;
const 2 = document . createElement ( ' p ' ) ;
p l . t extContent " ! " ;
p2 . textContent = " ! " ;

DOM 299
DOM
insertBe fore appendChi ld.
DOM ( <div id=" content " > ) .
cons t parent = document . getElementByid ( ' content ' ) ;
const firstChild = paren t . childNode s [ O ] ;

.
parent . insertBefore ( p l , firstChild ) ;
parent . appendChild ( p2 ) ;

inse rtBefore ,
. appendChild ,
(..
).


API DOM .

CSS. , ,
CSS, ( ),
. JavaScript,
CSS . , ,
, CSS.
. highlight {
background : # ffO ;
font-style : i t a l i c ;

<> ,
, highl ight. clas sList,
( ).
c l a s s L i s t add, .
,
highlightParas.
funct ion highlightPara s ( containing )
i f ( typeo f containing === ' string ' )
containing = new RegExp ( ' \ \$ { containing } \ \ ' , 'i');
const paras = document . getE lementsByTagName ( ' p ' ) ;
console . l og ( para s ) ;
for ( le t of para s ) {
i f ( ! containing . te s t ( p . textContent ) ) continue ;
p . classLi s t . add ( ' highl ight ' ) ;

300 1 8. JavaScript
highl ight Paras ( ' ' ) ;

, ,
classLi s t . remove.
function rernove ParaHighlight s ( )
const paras = docurnent . querySelectorAl l ( ' p . hi gh light ' ) ;
for ( let of para s ) {
p . classList . rernove ( ' highl ight ' ) ;

h i gh l i g h t
paras
remove ( ' highl i ght ' ) .
, .
,
, , , ,
. ,
, , queryS e lectorAll
.


HTMLS (data attribute),
L-;
, ,
JavaScript. L-,
, highl ightparas
remove ParaHighlights.
<button data-action="highlight " data-containing= " ya " >
, " "
</button>
<button data-act ion= " r ernoveHigh lights " >

< /button>

act ion conta ins ( ),


document . que rySelectorAll ,
"highlight " .

301
const highl ightAc t i ons document . querySelectorAl l ( ' [ data-
action= "highlight " ] ' ) ;

CSS.
, ,
.
". - .
,
querySelector querySe l e ctorAl l .
,
( : ,
, , ).
highlightAc t i ons,
, dataset.
highlightAct ions [ O ] . datas e t ;
/ / DOStringMap { con taining: " " , a c tion : "highligh t "

API DOM
( DOMSt r ingMap) .
,
. jQuery
, ,
, 1 9.

JavaScript, .
, ,
, .
highlightActions [ O ] . dataset . containing = " " ;
highli ghtAc t i ons [ O ] . dataset . caseSen s i t ive = " true " ;

API DOM 200 ,


, , ,
, , .
c l i ck. c l i c k
"" highl i ghtParas.
const highlightAct ions = document . querySelectorAll ( ' [ data-
action= " highlight " ] ' ) ;
for ( l e t of highl ightActions ) {
a . addEventLi stene r ( ' cl i ck ' , evt => {

302 1 8. JavaScript
evt . preventDefault ( ) ;
highlightParas ( a . dataset . containing ) ;
}) i

const removeHigh l i ghtActions =


document . querySe l e ctorAl l ( ' [ da ta-act ion=" removeHighlights " ] ' ) ;
for ( le t o f removeHighli ghtActions ) {
a . addEventListener ( ' cl i ck ' , evt = > {
evt . preventDe fault ( ) ;
removeParaHighlight s ( ) ;
}) i

addEventListener,
, i, .
- Event.
, .
, click clientX clientY,
, , target -
, click .
,
. ;
, <>,
, . ,
preventDefault ( ) .
, , preventDe faul t ( ) (
).

highl i ghtParas, containing
: ,
L-!


L- ,
. , ,
, , ..
, "
?"
, . -
. (capturing) .
<div id="conten t " >, , ,

303
<body>. <body>
, .
, ,
, .
(bubling) .
HTMLS
(
(target) ),
.

.
, , - preventDe faul t,
. ,
default Prevented t rue.
default Prevented ,
, . , ,
( ).
s t opPropa g a t i on,
. ,
, , , -
, . ( )
stopimmediatePropagat i on (
.
L-.
< ! doctype html>
<html>
<head>
< t i t l > < / t i t l >
<meta charset= "ut f- 8 " >
< /head>
<body>
<div>
<ut tn> ec ! </button>
</div>
< script>

11
funct i on logEvent ( handlerName , t ype , cance l ,
s t op , stopimmediat e ) {
1 1
return funct ion ( evt ) {
i f ( cance l ) evt . preventDefault ( ) ;
i f ( st o p ) evt . st opPropagation ( ) ;

304 1 8. JavaScript
i f ( stopirnmediat e ) evt . s t op irnmediat e Propaga t i on ( ) ;
console . log ( ' $ { type } : $ { handlerName } ' +
( evt . default Prevented ? ' ( ) ' : ' ' ) ) ;

1 1
function addEventLogger ( el t , t ype , act i o n ) {
const capture = t yp e === ' capture ' ;
e l t . addEventList ener ( ' cl i ck ' ,
l ogEvent ( elt . tagName , t yp e , a c t ion=== ' cancel ' ,
a c t i on=== ' st op ' , action=== ' st op ! ' ) , captur e ) ;

cons t body = document . querySelector ( ' body ' ) ;


con s t div = document . querySelector ( ' div ' ) ;
const butt o n document . querySel e ctor ( ' bu t t on ' ) ;
=

addEventLogger ( body, ' capture ' ) ;


addEventLogger ( body, ' u ' ) ;
addEventLogger ( div, ' capture ' ) ;
addEventLogger ( div, ' u ' ) ;
addEventLogger ( button, ' capture ' ) ;
addEventLogger ( button , ' u ' ) ;

< / s cript>
< /body>
</html>

, .
capture : BODY
capture : DIV
capture : BUTTON
u : BUTTON
u : DIV
u : BODY

,
. , ,
, ,
( ,
, ,
).
, .
, <di v>.
addEventLogger ( body, ' capture ' ) ;
addEventLogger ( body , ' u ' ) ;
addEventLogge r ( div, ' capture ' , ' cancel ' ) ;
addEventLogger ( di v , ' u ' ) ;
addEventLogger ( button , ' capture ' ) ;
addEventLogger ( button, ' u ' ) ;

, .
capture : BODY
capture : DIV ( )
capture : BUTTON ( )
u : BUTTON ( )
u : D IV ( )
u : BODY ( )

<button>.
addEventLogger ( body , ' capture ' ) ;
addEventLogger ( body, ' u ' ) ;
addEventLogger ( div, ' capture ' , ' cancel ' ) ;
addEventLogger ( div, ' u ' ) ;
addEventLogger ( button , ' capture ' , ' st op ' ) ;
addEventLogger ( button, ' u ' ) ;

, <button>.
<butt on> , ,
. <di v>
<body>, , .
capture : BODY
capture : DIV ( cancel e d )
capture : BUTTON ( canceled)
u : BUTTON ( canceled)


<button>.
addEventLogger ( body, ' capture ' ) ;
addEventLogger ( body, ' u ' ) ;
addEventLogger ( div, ' capture ' , ' cancel ' ) ;
addEventLogger ( div, ' u ' ) ;
addEventLogger ( button, ' capture ' , ' stop ! ' ) ;
addEventLogger ( button, ' u ' ) ;


<button>, .
capture : BODY
capture : DIV ( canceled)
capture : BUTTON ( canceled)

306 1 8 . JavaScript
addEventL i s tener
"on . . . ': ,
e l t
e l t . onclick function ( evt ) { / * * / } .
=

,
.

,
, ,
. ,
.

jQuery
fal se. s topPropagation
. jQuery,
I DOM.


MDN DOM,
. .



, dragstart, drag, dragend, drop .


,
(, ). focus ,
"" ( <>
), ur - "" ( - ,
<> ). change ,
.


(
<Enter> ),

submi t.


c l ic k,
(mou s e down, move, mou s eup, mou s eenter, mou s e l e ave, mous eover, mou s ewh e e l )

307
( ke ydown, keypre s s , keyup ) . , "
" ( )
, ,
. ,
, c l i ck.



HTMLS (pause, play ..).


.
l oad, ,
. error ;
, (,
).



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

Ajax
Ajax (Asynchronous Javascript And Xml)
-

. ,
,
. XMLHttpReques t
2000- "Web 2.0".
Ajax : JavaScript
- , ,
JSON ( JavaScript, XML).
.
Ajax ( ,
- Ajax),
. -
, .
Ajax, .
Node.js ( 20),

308 1 8. JavaScript
(endpoint) Ajax ( ,
). aj axServe r . j s .
const http = require ( ' ht tp ' ) ;

const server = http . createServe r ( funct ion ( req, re s ) {


res . s etHeader ( ' Content-Type ' , ' application / j son ' ) ;
res . s etHeader ( ' Acce s s-Contro l-Allow-Origin ' , ' * ' ) ;
res . end ( JSON . stringify ( {
plat form : proce s s . p l a t form,
nodeVe r s i on : proce s s . version,
upt ime : Mat h . round ( proce s s . upt ime ( ) ) ,
}));
}) ;

const port = 7 0 7 0 ;
server . l i s ten ( p o r t , function ( ) {
console . log ( ' Aj ax server s tarted on port $ { port } ' ) ;
});

, ("linux",
"darwin'; "win32" ..), Node . j s
.

Ajax ,
- (Cross-Origin Resource Sharing -
CORS). Acc e s s - Control
Allow-Origin *, ()
, -
.
, ( ),
, ,
. ,
CORS.


$ bael-node aj axServer . j s

http : / / localho s t : 7 07 0 , .
, , Ajax L- (
, ).
- , .
<div class=" serve r l nfo " >
<span data-replace= "plat form" > ? ? ? < / span> ,
Node < span data-replace="nodeVers ion " > ? ? ? < / span> .

Ajax 309
<span data-replace=" up t ime " > ? ? ? < /span> .
</div>

, , ,
XMLHttpRequest, j-.
L- ( < /body> ),
.
< script t ype= " application/j avascrip t ; version=l . 8 " >
function refreshSe rverinfo ( ) {
const req = new XMLHttpReque st ( ) ;
req . addEventListener ( ' l oad ' , funct ion ( )
/ / TODO: L-
console . log ( th i s . re sponseText ) ;
}) ;
req . open ( ' GET ' , ' ht tp : / / localhost : 7 0 7 0 ' , true ) ;
req . send ( ) ;

refreshServerinfo ( ) ;
< / script>

Ajax-.
XMLHttpRe que s t , ,
load ( , j- ).
( thi s .
re spons eText) . open,
. , -
GET. ,
( : POST, DELETE .).
URL . s end,
. ,
.
, ,
. - L-.
HTML , ,
replace,
. ,
( Ob j ec t . keys), -
replace,
.
req . addEventListener ( ' lo ad ' , function ( ) {
1 1 thi s . responseText - , JSON;
/ / JSON.parse ,
const data = JSON . parse ( t hi s . responseText ) ;

310 1 8. JavaScript
1 1 <div>,
1 1 "serverinfo "
const serverinfo = document . querySe l ector ( ' . se rverinfo ' ) ;

1 1 ,
1 1 ( "pla tform " , "nodeVers i on " "up t ime ") :
Obj e ct . keys ( d a t a ) . forEach ( p > {
=

1 1 ( )
cons t replacements =
serverinfo . queryS e le ctorAl l ( ' [ da ta-replace= " $ { } " ] ' ) ;
1 1 ,
for ( l e t r o f replacements ) {
r . t extContent = data [ p ] ;

});
});

refreshServe rinfo - ,
. ,
( upt ime ) . ,
( 200 ),
.
s e t interval ( refre shServerinfo, 2 0 0 ) ;

,
!

, , <div
class= " . serverinfo " >
.
,
, -
.
(Flash Of Unstyled Content - FOUC).

. - ,
.
, ,
.

,
j-.
" Using XMLHttpReqest" MDN.

Ajax 311
n
, , -,
JavaScript, .
, - -,
(Semmy Purewal) -
(Learning Web Development), CSS,
. (Eric . Meyer).

31 2 1 8 . JavaScript
1 9

jQuery

jQuery - DOM
j-. jQuery ,
API DOM ( , jQuery API DOM),
.
jQuery
, API DOM ( ).
jQuery API Ajax ( ,
- Ajax ).
j Query
API DOM.
-, ,
jQuery , API DOM
.
" JavaScript". , ( )
, .
, jQuery
, API DOM
. jQuery ,
- .

r ()
jQuery ,
JavaScript . ,
- , ,
jQuery, . jQuery
, j Query,
$.1 $ .
1 jQuery $ ,
(. jQuery. noConflict).
jQuery
jQuery -
CDN.
<s cript src= " / / code . j query . com/ j query-2 . 1 . 4 . min . j s " >< / s cript>

jQuery 2. Internet
Explorer 6, 7 8. ,
jQuery 1 .. jQuery 2.
, .

r DOM
, , L-,
, -
DOM ,
.
jQuery ,
, DOM.
$ ( document ) . ready ( funct i on ( ) {
1 1
/ / HTML DOM
});

,
jQuery
DOM. , .
$ ( function ( ) {
1 1
1 1 L- DOM
});


jQuery.

DOM jQuery
DOM jQuery -
DOM jQuery (jQuery-wrapped DOM elements).
DOM, jQuery,
jQuery, "" DOM ( ,
).

314 1 9 . jQuery
jQuery ($ j Query) DOM jQuery
( " jQuery" (jQuery
object); , jQuery DOM!).
jQuery : CSS
L-.
jQuery CSS jQuery,
( document . que rySelectorAl l ) . ,
jQuery, <>,
.
const $paras $ ( '' ) ;
=

$paras . lengt h ; / /
t ypeof $para s ; / / "obj ec t "
$paras instanceof $ ; / / true
$paras instanceof j Query; // true

jQuery L-, , DOM


HTML, ( ,
innerHTML ).
const $newPara = $ ( ' <> . . . </> ' ) ;

, ,
jQuery, . ,
.
, jQuery.

n n
, - jQuery,
? jQuery
. - L-
. ,
, .
jQuery text html,
textContent inne rHTML DOM.
, ,
$ ( 1 1 ) text ( ) ;
1 1

html, L-.
$ ( ' ' ) . html ( ' <i >BCE < / i > ' ) ;

: jQuery
. API DOM d o c ume n t .

315
queryS e l e ctorAll ( ) ,
- . jQuery
,
jQuery.
? jQuery eq,
jQuery, .
$ ('' ) / /
. eq ( 2 ) ! / ( )
. html ( ' <i>TPET < / i > ' ) ;

, remove jQuery.
.
$ ( ' ' ) . remove ( ) ;

j Query:
(chaining). jQuery jQuery,
, .
.
jQuery
. , append,
jQuery. ,
.
$ ('' )
. append ( ' < sup> * < / sup> ' ) ;

append ;
, before a fter.
, ( <hr> )
.
$('')
. a fter ( ' <hr> ' )
. be fore ( ' <hr> ' ) ;

appendTo,
insertBefore inse rtAfter, ,
, .
$ ( ' < sup > * < / sup> ' ) . appendTo ( ' ' ) ; 1 1 $ ( ' ' ) . append ( ' <s up>*</s up> ' )
$ ( ' <hr> ' ) . ins ertBe fore ( ' ' ) ; / / $ ( ' ' ) . before ( ' <hr> ' )
$ ( ' <hr> ' ) . insertAfter ( ' ' ) ; / / $ ( ' ' ) . after ( ' <hr> ' ) ;

jQuery .
, addC l a s s, , removeClass,
, toggleC l a s s ( ,

316 1 9 . jQuery
, , ).
, c s s .
: even : odd, . ,
,
.
$ ( ' p : odd ' ) . cs s ( ' color ' , ' red ' ) ;

jQuery -
. e q,
jQuery ;
f i l t e r, not f ind. f i l t e r
, . ,
f i l t e r ,
, .
$ ( '' )
. after ( ' <hr> ' )
. append ( ' <sup> * < / sup> ' )
. filter ( ' : odd ' )
. c s s ( ' color ' , ' red ' ) ;

not , , , filter. ,
-

<hr> , ,
highlight.
$ ( '' )
. a fter ( ' <hr> ' )
. not ( ' . highligh t ' )
. cs s ( ' margin-left ' , ' 2 0 ' ) ;

find ,
( filter,
). , <hr> ,
, code,
.
$ ( '' )
. be fore ( ' <hr> ' )
. find ( ' . code ' )
. c s s ( ' font - s i z e ' , ' ' ) ;

jQuery
"" jQuery ( DOM)
, get. DOM .

jQ uery 317
const para2 = $ ( ' p ' ) . ge t ( l ) ; / / <> ( )

, DOM .
const paras = $ ( ' ' ) . ge t ( ) ; / / <>

Ajax
jQuery , j-. jQuery
aj , j-.
get post, j-
. ,
,
. , get,
refreshServerinfo .
funct ion refreshServerinfo ( ) {
const $ s e rverinfo = $ ( ' . server i nfo ' ) ;
$ . ge t ( ' http : / / l ocalhost : 7 0 7 0 ' ) . then (
1 1
function ( da t a ) {
Obj ect . keys ( data ) . forEach ( p => {
$ ( ' [ data-replace=" $ { p } " ] ) text ( data [ ] ) ;
' .

});
},
function ( j qXHR, t ex tStatus , err) {
conso l e . error ( e rr ) ;
$ serve rinfo . addClas s ( ' error ' )
. html ( ' . ' ) ;

);

, jQuery Ajax.


jQuery . API JavaScript
jQuery? " JavaScript"?
. , jQuery
. , jQuery ,
.
jQuery,
jQuery 2.0 (. , "'; 2016, ISBN 978-5-8459- 1919-9).
jQuery .

318 1 9. jQuery
20

Node

2009 JavaScript
.1 2009 Joyent (Ryan
Dahl), - , Node.
Node
.
, JavaScript , Node
, . -
, .
JavaScript .
,
(, , )
, .
Node ,
-,
,
. Node JavaScript
.

Node
Node
JavaScript. ,
JavaScript-popay Node,
JavaScript API, .
, Node DOM ( , L-
!). Node API,
Node . ,

1 JavaScript Node; , Netscape


Enterprise Server JavaScript 1 995 . JavaScript
2009 , Node.
,
( , ,
?).
, -, .
, JavaScript API.
, , ,
window docurnent - JavaScript. API,
( 1 8) .
API, Node.
, Node npm (. 2).

n
-
. (namespacing) -
. ,
calculate, ,
.
calculate " " calculate " ".
, Node . amanda .
j s.
function calculate ( , , n ) {
i f ( x === 1 ) return a * n ;
return a * ( l - Mat h . pow ( x , n ) ) / ( 1 - ) ;

module . exports = calculate ;

tyler . j s .
function calculat e ( r ) {
return 4 / *Math . PI *Math . pow ( r , 3 ) ;

modu le . exports = calcula t e ;

,
, .
- module . exports = cal culate ; .
modul e - , Node
. , export s,
. , , ,

320 20. Node


. . j s,
.
const amanda_calculate = require ( ' . /amanda . j s ' ) ;
const t yler_calculate require ( ' . /t yler . j s ' ) ;
=

console . log ( amanda_calculate ( l , 2 , 5 ) ) ; // 3 1


consol e . log ( t yler_calculate ( 2 ) ) ; // 33 . 51 0321 638291 1 24

, (amanda_ c a l cu l a t e t y l e r_
calculate) ; .
Node require.
, ,
: + + 2 + ... +
-1, r. , ,
,
. j s .
const geometricSum = require ( ' . /amanda . j s ' ) ;
const sphereVolume = require ( ' . / t yl er . j s ' ) ;

consol e . log ( geometricSum ( l , 2 , 5 ) ) ; / / 31


console . log ( sphereVolume ( 2 ) ) ; / / 33 . 51 0321 638291 1 24

( ,
). ,
. .
, - ,
,
.
module . exports ={
geometricSum ( a , , n ) {
i f ( x === 1 ) return a * n ;
return a * ( l - Math . pow ( x , n ) ) / ( 1 - ) ;
},
a r ithme t i cSum ( n ) {
return ( n + l ) * n / 2 ;
},
quadrat i c Formul a ( a , , )
const D = Math . sqrt ( b * b - 4 * * ) ;
return [ ( - + D ) / ( 2 * a ) , ( - - D ) / ( 2 * a ) ] ;
},
};

-
, , ()
.

321
const amanda = require ( ' . / amanda . j s ' ) ;
console . log ( amanda . geometricSum ( l , 2 , 5 ) ) ; / / 31
console . log ( amanda . quadraticFormul a ( l , 2, - 1 5 ) ) ; / / [ 3 , - 5 }

:
( S
; , ).
, ,
exports.
.
export s . geometricSum funct ion ( a , , n) {
=

i f ( x === 1 ) return a * n ;
return a* ( l - Math . pow ( x , n ) ) / ( 1 - ) ;
};

exports . ari thme t i cSum function ( n ) {


return ( n + l ) * n/ 2 ;
};

expor t s . quadr a t icFormu l a = function ( a , , )


const D = Math . sqrt ( b * b - 4 * * ) ;
return [ ( - + D ) / ( 2 * ) , ( - - D ) / ( 2 * ) ] ;
};

"expo rts" ;
,
module . export s . , :
, .

, n m -n
: (core module), 1 (file module)
- (npm module). ; ,
, fs o s, Node (
). ,
, module . export s ,
. npm -
, , node _modules.
require, Node (
. 20. 1 ) .

322 20. Node


n 20.1 . n
, require
/, . / . . / require ( ' fs ' )
require ( ' os ' )
require ( ' http ' )
require ( ' chi ld_process ' )
- /, . / . /
. require ( ' . /debug . j s ' )
require ( ' / full /path/to/module . j s ' )
require ( ' . . / a . j s ' )
requi re ( ' . . / . . / . j s ' )
npm requi re ( ' debug ' )
/, . /
. /. require ( ' express ' )
require ( ' chal k ' )
require ( ' koa ' )
require ( ' q ' )

, process buffer, .
require.
. 20.2.
n 20.2. n
n nn
as sert
buffer - (1/0) (
, )
child_process (Node .)
cluster

crypto
dns (DNS)

domain -

events
fs
http
https S
net API
os
path
punycode U nicode
ASCll
querystring URL

, n m - 323
. 20.2


readline -;
,
smal loc
s tream
s tring_decoder
tls TLS (Transport Layer Security -
)
tty Y(eleTYpewriter)
dgram UDP (User Datagram Protocol -
)
url URL
util Node
vm (JavaScript):

z lib

.
,
.
API Node (https : / /nodej s . o rg/api/).
, - -
. ( -
), Node node_modules.
, . ,
, node _modules
. ,
. ,
/ home / j doe / t e s t_pro j ect
requi re ( ' ' ) , Node
.
/home/ j doe/test_proj ect /node_modules/x
/home / j doe /node_modules/x
/home/node modules /x
/node modules/x

node modules
_

. ,
; npm .

324 20. Node


, Node ,
.
, , node _modules.
, node _modules ,
npm ,
package . j son (. 2).
, , npm
, npm,
node_modules!

n
n -
, .
- ,
, . ,
,
. , ,
, , .
,
.
npm debug. debug ,
.
,
.
const debug = require ( ' debug ' ) ( ' ma in ' ) ; 11 ,

1 1 ,
/ /

dug ( " " ) ; / /


1 1 "ma in +Oms " ,
1 1

debug,
DEBUG.
DEBUG=main. DEBUG=*,
.

, debug (
)".
, "" , .

- 325
"" . ,
debug.
l e t l a s tMe ssage ;

module . exports = function ( prefix )


return function (mes sage ) {
const now = Date . now ( ) ;
const s inceLastMe s sage now - ( la s tMessage 1 1 now) ;
console . log ( ' $ { prefix } $ {mes sage } + $ { s inceLa s tMe s sage } ms ' ) ;
l as tMessage = now ;

, ,
prefix . ,
, lastMessage,
, ; ,
.
: ,
? , ,
debug .
const debugl require ( ' . /debug ' ) ( ' ' ) ;
const debug2 require ( ' . / debug ' ) ( ' ' ) ;

debugl ( ' ! ' )


dug2 ( ' ! ' )

setTimeout ( function ( ) {
debugl ( ' poo . . . ' ) ;
debug2 ( ' o ? ' ) ;
} 200 ) ;
,

:
! + Oms
! + Oms
. . . + 2 0 0ms
? +2 0 0ms

. (
).
! + Oms
! + Oms
. . . + 2 0 0ms
? + Oms

326 20. Node


, Node
Node. , ,
debug , Node "': ,
. , , debugl debug2 -

,
lastMes sage.
.
, ,
!

,
debug, ,
nm-.
,
l a s tMes s age, , -
, .
,
.

n

, ""
. JavaScript: Node
.
,
/home/ <jdoe>/ fs. Unix,
<jdoe> .
Windows (
: \Users\ <John Doe>\Documents \ fs).
, fs . writeFile.
write . j s.
const fs = require ( ' fs ' ) ;

f s . wri teFile ( ' he l l o . txt ' , ' Node ! ' function ( e r r ) {


,

i f ( err) return console . log ( ' Oa . ' ) ;


});

hello . txt ,
wri te . j s. ,

327
hello . txt. Node,
, ,
, .
$ cd /home / j do e / f s
$ node write . j s # /home/jdoe/fs
# /home/jdoe/fs/hel l o . txt

$ cd . . # /home/j doe
$ node fs /write . j s # /home/jdoe/hello . tx t

Node , _d i rname,
, . ,
.
const fs = require ( ' f s ' ) ;

fs . writeFile ( _dirname + ' /hel l o . txt ' ,


' Node ! ' , funct ion ( err)
i f ( er r ) return console . error ( ' Oa . ' ) ;
});

wri te . j s hel l o . txt


/home / < j doe>/ fs ( write . j s) .
_di rname -
. Windows,
. Node path

. , ,
.
const fs = require ( ' fs ' ) ;
const path = requ i re ( ' path ' ) ;

fs . writeFi l e ( path . j oi n (_dirname , ' he l l o . t xt ' ) ,


' Node ! ' , function ( err )
i f ( err ) return consol e . error ( ' Oa . ' ) ;
});

path . j oin ,
, ,
.
?
fs . readFile. read . j s.
const fs = require ( ' fs ' ) ;
const path = requ ire ( ' path ' ) ;

328 20. Node


fs . readFi l e (path . j oin (_dirname , ' he l l o . txt ' ) , function ( err, dat a )
i f ( er r ) return console . error ( ' Oa . ' ) ;
console . log ( ' Coepoe : ' ) ;
console . log ( data ) ;
));

, .
:
< Buffer dO 9f dl 8 0 dO 8 dO 2 dO bS dl 8 2 2 0 dO 8 dO 7 2 0 4 6f 64 65 2 1 >

ASCII/Unicode,
, Node ! ,

.
fs . readFile , ,
, "" .
wri te . j s ,
JavaScript UTF-8 ( Unicode). read . j s,
UTF-8, .
const fs require ( ' fs ' ) ;
=

const path require ( ' th ' ) ;


=

fs . readFile (path . j oin (_dirname , ' he l l o . txt ' ) ,


{ encodin g : ' ut f 8 ' ) , function ( err, dat a )
i f ( err) return consol e . error ( ' Oa . ' ) ;
console . log ( ' Coepoe : ' ) ;
console . log ( data ) ;
));

f s (
"Sync"). wri te . j s .
fs . writeFileSync (path . j o in (_dirname , ' he l l o . txt ' ) , ' Node ! ' ) ;

read . j s .
const data = f s . readFileSync ( path . j oin (_dirname , ' he l l o . txt ' ) ,
encoding : ' ut f 8 ' ) ) ;


, ,
t ry/catch, .
t ry {
f s . writeFi l e S ync ( path . J oin (_dirname , ' he l l o . txt ' ) , ' Node 1 ' ) ;
catch ( err) {
console . error ( ' Oa . ' ) ;

329
.
- , ,
.
-
-. ,
.

fs . readdir, .
l s . j s.
const f s = require ( ' fs ' ) ;

f s . readdir (dirname , function ( er r , file s ) {


i f ( er r ) return console . error ( ' Heooo ' ) ;
console . log ( ' Coepoe $ { dirname ) : ' ) ;
console . log ( fi l e s . map ( f => ' \ t ' + f ) . j oin ( ' \n ' ) ) ;
)) ;

f s ;
(fs . unl ink), (fs . rename),
(fs . stat) .
Node API (https : / /nodej s .
org/ap i / fs . html) .

proces s
Node process,

. , , ,
(
(fatal error)), ,
process . exit. (exit code),
, .
" ':
. , . txt
data: ,
, . ,
da ta , ,
. .
const fs = require ( ' fs ' ) ;

fs . readdir ( ' data ' , funct ion ( er r , f i le s ) {


i f ( er r ) {

330 20. Node


consol e . error ( " Oa : data . " ) ;
proce s s . exit ( l ) ;

const txtFi les = f i le s . f i l t e r ( f => / \ . txt $ / i . t e s t ( f ) ) ;


i f ( txtFile s . length === 0 ) {
console . log ( " . txt . " ) ;
proces s . ex i t ( O ) ;
}
/ / txt . . ..

});

process ,
, . Node,
. ,
,
, .
.
$ node linecount . j s filel . txt file2 . txt file . txt

proces s . a rgv.2
, proces s .
argv, , .
console . log ( proce s s . argv ) ;

filel . txt, file2 . txt file . txt


.
' node ' ,
' /home / j do e / l inecount . j s ' ,
' f i l e l . txt ' ,
' file2 . txt ' ,
' fi l e . txt ' ]

- , ,
( - node). -
,
. -
, Array . s l i ce, ,
.
const fs = require ( ' fs ' ) ;

const filename s = proce s s . argv . s l i ce ( 2 ) ;

2 argv - . v - vector (),


.

process 331
l e t counts = fil ename s . map ( f => {
try {
const data = fs . readFileSync ( f , { encoding : ' ut f 8 ' }) ;
return ' $ { f } : $ { da t a . sp l i t ( ' \n ' ) . length} ' ;
catch ( er r ) {
return ' $ { f } : ' ;

}) ;

console . log ( count s . j oin ( ' \n ' ) ) ;

process
proces s . env.
, .
U11ix ,
export = (
). Wi11dows
set = .
,
.
, m
.
DEBUG, 1, ,
( ).
cons t debug = proce s s . env . DEBUG === " 1 " ?
consol e . log :
funct ion ( ) { } ;

dug ( " , DEBUG=l ! " ) ;

, debug,
console . log, DEBUG ,
( ) (
debug , ,
!).
,
( , .
). proce s s . cwd ,
process . chdir . , ,
, ,
, .
console . log ( ' Tey : $ { process . cwd ( ) } ' ) ;
proces s . chdir (dirname ) ;
console . log ( ' Ho : $ { proce s s . cwd ( ) } ' ) ;

332 20. Node



os
, . ,
, os ,
.
cons t os = require ( ' os ' } ;

console . log ( " : " + os . hostname ( } } ; 1 1 prometheus


console . l og ( " : " + os . type ( } } ; 1 1 Lin ux
nsl . l g ( " : " + os . platform ( } } ; 1 1 l i n ux
console . log ( " Bepc : " + os . release ( } } ; 1 1 3 . 1 3 . 0-52-generic
console . log ( " Bpe : " +
( o s . upt ime ( ) / 6 0 / 6 0 / 2 4 ) . toFixed ( l } + " days " } ; 1 1 8 0 . 3 days
console . log ( "Apxe ypa : " + os . arch ( } } ; / / 64
nsl . l g ( " : " + os . cpus ( } . length } ; // 1
console . l og ( " Oe : " +
( o s . totalmem ( } / l e 6 } . toFixed ( l } + " " } ; 1 1 1 042 . 3
consol e . log ( " Cooo : " +
( o s . freemem ( } / l e 6 } . t oFixed ( l } + " " } ; 1 1 1 95 . 8


chi ld_process
, Node,
.
, .
child_process : , exec F i l e
fork. fs, ( execSync,
execFi leSync forkSync ) . execFi le
, .
( ,
; ,
). execFile
;
, . fork
Node ( ).

fork Node,
, ;
fork
(interprocess communication).

333

(https : / /nodej s . org/ap i / child_proce s s . html #child_
proces s_child_process fork_modulepath_args _options).

,
.
dir,
( Unix l s ,
Unix dir).
const = require ( ' child_proces s ' ) . ;

exec ( ' di r ' , function ( err, s tdou t , stder r ) {


i f ( er r ) return console . error ( ' Oa "dir" ' ) ;
stdout = stdout . toString ( ) ; / / Buffer
console . log ( s tdout ) ;
stderr = s tderr . toString ( ) ;
i f ( s tderr ! == ' ' ) {
console . error ( ' Oa : ' ) ;
consol e . error ( stderr ) ;

});

,
, .
, ,
.

Buffer - s tdout ( )
s tderr ( , ).
, stde rr,

, .
options,
, ..
(https : / /node j s . org/
api / child_process . html).

,
. child_proces s ,
const child_process = require ( ' child_proces s ' ) ,
child_proces s . ,
.
, , , .

334 2 0 . Node

(stream) Node. - ,
( ) (
, - ,
, ).
, (
). ,
.
- .
( ,
) .
, ,
(pipe) .
.
const fs require ( ' fs ' ) ;

const ws fs . createWriteStream ( ' stream . tx t ' , { encodin g : ' ut f 8 ' } ) ;


ws . write ( ' 1 \ n ' ) ;
ws . write ( ' 2 \ n ' ) ;
ws . end ( ) ;

end ,
wri te. ,
,
end , .

(write stream - ws)


write end, ,
wri te . wri te
, , end,
.
,
.
const fs require ( ' fs ' ) ;

const rs = fs . creat eReadStream ( ' s tream . txt ' , { encodin g : ' ut f 8 ' } ) ;
rs . on ( ' da ta ' , funct i on ( da t a ) {
console . log ( ' >> : ' + dat a . replace ( ' \n ' , ' \ \n ' ) ) ;
});
rs . on ( ' end ' , function ( da t a )
console . l o g ( ' >> ' ) ;
});

335
(
).
: , ,
, .

. , wri te,
, data end.
"': ,
, .
(piping). , ,
.
const rs = f s . createReadStrearn ( ' strearn . txt ' ) ;
const ws = f s . createWriteStrearn ( ' strearn_copy . txt ' ) ;
rs . pipe ( ws ) ;

,
: rs s t ream . txt ws (
s tream_ . txt); ,
.
- .
, -.
, , ,
.

-
Node ,
-. ,
.
, Apache ( IIS, - ),
-.
http ( , https)
createServer, -. , , -
,
. , l is ten
.
const h t tp = require ( ' http ' ) ;

const s erver = http . createServer ( funct i on ( req, res ) {


console . log ( ' $ { re q . rnethod } $ { req . url } ' ) ;
rs . nd ( ' , ! ' ) ;

336 20. Node


});

const port = 8080;


server . li s t e n ( port , funct ion ( ) {
1 1 l i s ten ,
1 1
console . log ( ' Cepep $ { port } ' ) ;
});


(80)
.
1 024. ,
: sudo,
sudo , ,
80.
1 024. , 3000,
8000, 3030 8080, .

http : / /
localhost : 8 0 8 0, , ! .
, URL. ,
URL,
.
GET /
GET / favicon . ico

,
URL .
.
- Node ,
. .
, I ncomingMes sage (
req) ServerRequest (
res ) . I ncomingMes sage -:
URL , , ..
ServerResponse ,
( ). ,
req . end, " req ?':
. ServerResponse
, , .
ServerResponse - , ...

- 337
-. , favi con . ico,
-, -
.
const s e rver = h t tp . createServer ( function ( req, re s ) {
i f ( re q . me thod
=== ' GET ' && r e q . url
=== ' / favicon . ico ' )
const fs = require ( ' fs ' ) ;
fs . createReadStream ( ' favicon . ico ' ) ;
fs . pipe ( re s ) ; / / ' en d '
else {
console . log ( ' $ { re q . method } $ { re q . url } ' ) ;
res . end ( ' He l l o world ! ' ) ;

});

, , -.
, IncomingRequest,
- .
Node -, ,
, , Express ,
- .

- Express,
: .
Express, ,
, -,
S.


API Node.
, , ,
(, f s , Buffer, proc e s s stream).
, .
(ht tps : / / nodej s . o rg / en/ docs / ) - ,
. Node,
(Shelley Powers) Learning Node.

338 20. Node


21

:
: (data property)
(accessor property). ,
S (
9 " ").
( );
, ( (getter)
(setter)), ,
.
. User
setEmai l getEmail. "get" "set"
ema i l ,
. (
, " @ "
).
const USER EAIL = Symol ( ) ;
c l a s s User {
setEmai l ( va lue ) {
i f ( ! / @ / . te s t ( value ) ) throw new rrr ( ' : $ { value } ' ) ;
this [ USER_EAI L ] = value ;

getEma i l ( )
return t h i s [ USER_EAI L ) ;
, (
), -
USER_EMAI L .
, ,
.
ema i l _ema i l,
.
, ,
, . .
const u = new U s e r ( ) ;
u . setEmai l ( " j ohn@doe . com" ) ;
console . log ( ' Ape c : $ { u . getEma i l ( ) } ' ) ;

,
const u = new User ( ) ;
u . emai l = " j ohn@doe . com" ;
console . log ( ' Apec : $ { u . email } ' ) ;

:
. ,
.
const USER_EAIL = Symol ( ) ;
class User {
s et ema i l ( value ) {
i f ( ! / @ / . te s t ( value ) ) throw new rrr ( ' : $ { value } ' ) ;
this [ USER_EAIL ] = value ;

get ema i l ( ) {
return this [ USER_EAI L ] ;

, ema i l .
,
( ),
, .
- - ;
, , -,
.
class Rectangle
constructor ( wi dt h , hei gh t )
thi s . width = width ;
thi s . height = height ;

340 2 1 . -
get perimeter ( ) {
return thi s . width* 2 + this . height * 2 ;

- ,

; .
- -,
.


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

).
( ,
, ,
, ).
, . ,
, ,
. ,
, Obj ect . getOwnPropertyDes criptor
.
const obj = { foo : "bar" } ;
Obj ect . getOwnPropertyDes criptor ( obj , ' foo ' J ;

.
value : " bar " , writa e : true , e numera e : t rue , configurae : true }

(property attribute),
(property descriptor) (property configuration)
; .

.
writae () ,
.

341
enumerae () ,
( for . . . in, Obj ect .
keys ).
configurae () ,
.

, Obj ect . de f i ne
P roper t y.
( ).
, foo obj
, Obj ect . defineProperty .
Obj ect . definePropert y { ob j , ' foo ' , { writa e : false } ) ;

, foo, .
obj . foo = ;
11
TypeError : ' foo ' ,


.
, .

Obj ect . def ineProperty


. ,

, . obj color (
).
Obj ect . de f inePropert y { ob j , ' co l or ' , {
get : function { ) { return thi s . color ; } ,
set : function { value ) { thi s . color = value ; } ,
});

,
Obj ect . defineProperty. obj name greet.
Obj ect . defineProperty { ob j , ' name ' , {
value : ' Cynthia ' ,
});
Obj ect . defineProperty { ob j , ' greet ' , {
value : funct ion ( ) { return ' , $ { thi s . name } ! ' ; }
});

Obj ect . de f ine Property -

. ,

342 2 1 . n -
,
, ,
. for . . . in Obj ect . keys
( for, for . . . of
Arra y . prototype . forEach), .
, ,
, - ( ) for . . . in
Obj ect . keys. sum avg.
const arr = [ 3 , 1 . 5 , 9 , 2 , 5 . 2 ] ;
arr . sum = funct ion ( ) { return t hi s . reduce ( ( a , ) => + ) ;
arr . avg = functi on ( ) { return this . sum ( ) /thi s . length;
Obj ect . defineProperty ( arr, ' sum ' , { enumerae : false } ) ;
Obj ect . defineProperty ( arr, ' avg ' , { enumerale : false } ) ;

r .
const arr = [ 3 , 1 . 5 , 9, 2 , 5 . 2 ] ;
Obj ect . defineProperty ( ar r , ' sum ' , {
value : funct ion ( ) { return thi s . reduce ( ( , ) => + ) ; ) ,
enumerae : f a l s e
});
Obj ect . define Property ( arr, ' avg ' , {
value : function ( ) { return this ; sum ( ) /thi s . l ength ; } ,
enumera e : f a l s e
}) ;

Obj ect . defineProperties (


!),
. ,
const arr = [ 3 , 1 . 5 , 9 , 2 , 5 . 2 ] ;
Obj ect . definePropert i e s ( arr,
sum : {
value : function ( ) { return t hi s . reduce ( ( , ) => + ) ; } ,
enumerae : false
}) ,
avg : {
value : funct ion ( ) { return this . sum ( ) /thi s . length ; } ,
enumera e : fal s e
})
);

: ,

JavaScript ,
.

: , 343
, ,
, , , .
JavaScript
( ): (freezing),
(sealing) (preventing extension).
.
,
;
, ;
(
);
;
;
.

, .
-, ,
, .
, Obj ect . freeze ( ,
, Obj ect . i sFrozen). , ,
,
(, , ,
).
con s t appi nfo = {
compan y : ' Wh i t e Knight Softwa r e , Inc . ' ,
version : ' 1 . 3 . 5 ' ,
bui ldi d : ' Oa 9 9 5 4 4 8 -ead4- 4 a 8b-b05 0 - 9 c9 0 8 3 2 7 9ea2 ' ,
/ / ,
/ !
copyright ( ) {
return ' $ { new Date ( ) . ge t FullYear ( ) } , $ { th i s . compan y } ' ;
},
};
Obj ect . free z e ( appinfo ) ;
Obj ect . i s Frozen ( appinfo ) ; / / true

appi n fo . newProp = ' te st ' ;


/ / TypeError : newProp,

del e t e appinfo . compan y ;


/ / TypeError : ' '

344 2 1 . -
app i nfo . company = ' te s t ' ;
/ / TypeError : ' '

Obj ect . defineProperty ( appinfo, ' company ' , { enumerae : false } ) ;


/ / TypeError: :

,
. ,
, , (
, ).
Obj ect . seal, , , -
Obj ec;t . i sSealed:
c la s s Logger {
cons t ructor ( name )
this . name = name ;
this . log = [ ] ;

add ( entry) {
this . log . push ( {
log : entry,
t ime stamp : Date . now ( ) ,
}) ;

const log = new Logger ( " " ) ;


Obj ect . seal ( log) ;
Obj e ct . i s Sealed ( log ) ; / / true

log . name = " " ; / /


log . add ( " Ee . . . . " ) ; / /

log . newProp = ' te st ' ;


/ / TypeError : ewProp ,

log . name = ' te s t ' ; / /

delete l o g . name ;
/ / TypeError : ' '

Obj ect . defineProper t y ( log, ' log ' , { enumerae : false } ) ;


/ / TypeError: : log

- ,
. ,
.

: , 345
Obj ect . preventExtens ions Obj ect . i sExtensie
Logger.
const log2 = new Logger ( "ypa " } ;
Obj e ct . preventExtensions ( log2 } ;
Obj ect . i sExtensile ( log2 } ; / / true

log2 . name = " " ; //


log2 . add ( "Ee . . . . " } ; / /

log2 . newProp = ' te s t ' ;


/ / TypeError : newProp,

log2 . name = ' te st ' ; 1 1


delete log2 . name ; 1 1
Obj ect . definePropert y ( log2 , ' log ' ,
{ enumerae : false } } ; 1 1

Obj ect . preventExtensions .



, .
. 2 1 . 1 .
2 1 .1 .
- - w-





-
- (proxy) - S,
uu (metaprogramming),
.. .
-, , ()
. :
. , .
const coefficients = {
: 1,
: 2,
: 5,
};

346 2 1 . -
,
. .
funct ion evaluat e ( x , ) {
return . + . * + . * Math . pow ( x , 2 ) ;

".
.
?
const coeff icients = {
: 1,
: 3,
};
evalua t e ( S , coe fficients ) ; / / NaN

, coe fficient s . ,
- .
, ,
. -
coe fficients.
const betterCoefficients new Proxy ( coefficients ,
=

get ( targe t , key ) {


return t arget [ ke y ] 1 1 ;
},
});

-
Babel. Firefox,
.

Proxy (target), ,
-

-. (handler),
-

.
, get.
get . . ,
.

, . get (
): , ( )
( - ).
, ,
, . .
betterCo e f f i c i ent s . a ; 11 1
betterCoefficients . b ; 11
betterCoe fficient s . c ; 11 3

- 347
bet terCoeffi cient s . d ; //
betterCoeffi cient s . anything ; // ;

, - coe fficients,
(
, , )!
-,
, .
const betterCoe fficient s = new Proxy ( coefficient s , {
get ( t arge t , key ) {
i f ( ! / [ a- z ] $ / . te s t ( ke y ) ) return target [ ke y ] ;
return target [ ke y ] 1 1 ;
},
}) ;

target [ key]
, . ..
.
( ),
set. ,
.
- .
, ,
allowDangerousOperations t rue.
const cook = {
name : "Wal t " ,
redPhosphorus : 1 0 0 , / /
water : 5 0 0 , / /
};
con s t protect edCook new Proxy ( cook,
set ( targe t , key, value ) {
i f ( ke y === ' redPhosphorus ' ) {
i f ( target . a l lowDangerousOperations )
return t arget . redPhosphorus = value ;
else
return console . log ( " Oe ! " ) ;
}
/ /
targe t [ ke y ] = value ;
},
}) ;

protectedCoo k . water = 5 5 0 ; 11 550


protectedCook . redPhosphorus 1 5 0 ; // !

348 21 . -
protectedCook . al lowDangerousOperat ions = true ;
protectedCook . redPhosphorus = 1 5 0 ; / / 1 50


. ,
(Axel Rauschmayer) Meta Prograrnrning with ECMAScript 6 Proxies (http : / /www . 2ality .
com/ 2 0 1 4 / 1 2 / e s -proxie s . h tml ) , MDN (https://
developer. mozilla.org/ru/docs/WebIJavaScript/Reference/Global_Objects/Proxy).


,
JavaScript, ,
. , .
S
-

. - r
, ,
S.

349
22

, JavaScript - ,
. "" ,
" ". ,
!
,
JavaScript, ,
. JavaScript - ,
. , ,
, .
Web
-

Developent with Node and Express ( O'Reilly).


JavaScript, CSS HTML Mozilla (Mozilla
Developer Network - MDN, https : / / developer . mo z i l la . org/ru/) .
JavaScript, MDN,
"mdn" .
w3schools.
SEO w3schools, , ; ,
.
MDN - HTML, HTMLS
( ),
HTMLS CSS . WATWG
HTML5 (https : / /developers . whatwg . org/);

HTML. HTML
CSS, - W; , ,
.
S -262 ECMAScript 2015 Lagage
Specificatio (http : / / www . ecma-internat ional . o rg / ecma- 2 62 / 6 . /) .
S Node ( )
, @kagax (h t t : / / kang . g i thub . i /
compat-tale / e s / ).
jQery (ht tp : / / api . j que ry . com/ ) Bootstrap (http : / / getbootstrap . com/)
.
Node (https : / /node j s . org/api /)
,
Node (, http, http fs).
(https : / /docs . npmj s . com/) ,
package . j son (https://docs.npmjs.com/getting-started/using-a
package.json).


,
.
JavaScript Weekly (http : / / j avascriptweekly . com/)
Node Weekly (http : / /nodeweekly . com/)
HTMLS Weekly (http : / / frontendfocus . co/)

, ,
.

6nor
- JavaScript.
.
(Axel Rauschmayer, http : / /www . 2ality. com/)
S . -
JavaScript ,
,
, .
(Nolan Lawson, h t tps : / /nol anl awson . com/)

JavaScript. We Have r with Promises (https : / /pouchdb .
com/ 2 0 1 5 / 0 5 / 1 8 /we-have - a-pro em-wi th-p romi s e s . html )
.

352 2 2 .
(David Walsh, https : / /davidwal s h . name / )
JavaScript
. 1 4,
The Basics of S Generators (http s : / /
davidwalsh . name/es6-generators).
@ kangax, Perfection Kills (http : / /perfect ionki l l s . com/),
, .
, .

, ,
. ,
,
, .
Lynda.com JavaScript (https : / /www . lynda . com/ JavaScript-training
tutorials / 2 4 4 - 0 . html) .
Treehouse JavaScript (htt ps : / / t e amtreehouse . com/ l e a rn-to-code/
j avascript).
Codecademy's JavaScript ( h t t p s : / / www . c od e c a demy . c om/ l e a rn /
j avascript).
Microsoft Virtual Academy's intro course JavaScript (https : / /
mva . mi c rosoft . com/en-U S / t ra ining-course s / j avascript-fundamenta l s
for-absolute-beginners- 1 4 1 9 4 ). JavaScript
Windows, Visual Studio
JavaScript.

Stack Overflow
,
Stack Overflow (SO). 2008 ,
,
, JavaScript (
, ). Stack Overflow -
. -
, .
""
. , ,
. , ,
, .

Stack Overflow 353


- Stack Overflow. , -
, -
, . SO
, ,
/ ( ,
, ). ,
.


SO tour (http : / / stackoverflow . corn/tour),
How do I ask good question? ( ?, http : / /
stackoverflow . corn/help/how-to-ask). ,
(help docuentation, http : 1 1 stackoverflow . corn/help)
!

,
; , -
. , SO,
, ,
.


, "" ,
" ":' SO ,
, SO.
, .


(" ". ".
- ?") ; .


SO,
, ( ! ) .
5000 SO
-

( ). "" ,
.
, ,
, (
SO).
, SO.

354 22 .
Markdown
Stack Overflow
Markdown. ,

.


- ,
; SO.
, ,
, , , , ,
.

,

SO - ; , ,
- . ,

.
, :
, , ,
. ,
, (bounty) ,
.
, . -
, . ,
: - 50
. , ,
, , .
,
. , , ,
.
, ,
SO. , , ,
, , .
,
. , , .
, , ,
SO ( SO 3000;
- ). SO ,
, .

Stack Overflow 355


Source
-
: ,
, ,
. .
, - -
.
, : -
, , .

,
, , .
Bringing indness Back to Source (http : / /www . hanse lman . com/
og/BringKindnes sBackToOpenSource . a spx) (Scot
Hanselman). - for Grabs (http : / /up-for-grabs .
net),
. "JavaScript'',
,
.


JavaScript!
, , ,
,
. , ! JavaScript -
, ( ).
, , ,
; ,
.
S ,
. , ,
JavaScript, ,
, . JavaScript
, , .

356 22.


( , , ) JavaScript.
await ( )
break
case
class
catch
const
continue
debugger
default
delete
do
else
enum ( )
export
extends
false ( )
finally
for
function
if
implements ( )
import
in
instanceof
interface ( )
let
new
null ( )
package ( )
private ( )
protectd ( )
pui c ( )
return
super
s tatic ( )
switch
this
throw
t rue ( )
t ry
typeof
var
void
whi l e
with
yield

ECMAScript 1 -3. ,
, JavaScript
.

358 .
abstract
boolean
byte
char
doue
final
float
goto
int
long
native
short
s ynchroni zed
t rans ient
volat i l e

. 359

. . 1 Mozilla Developer Network


. ES7 .
.1 . ( 1 9 ) ()

19 (. .) .

18
". [".]
new ( ) new . . . ( . . ) .

17 " ( .) . "

new ( ) new . . .
16 . . . ++

15 NOT ! . .

NOT
+" .

++. . .

typeof typeof . . .
void void . . .
delete delete . . .
14 . .*. . . .

. "/" .
g.

13 . "+ " .
-
. . ..
. .

12 . . . << . . .

. . 1


. . . >> . . .

- . . . >>> . . .

11 . . .<. . .
. . . <= . . .
. . .>. . .
. . . >= . . .
in . . . in . . .
instanceof . . . inst anceof . . .
10
. . . ! =. . .

. . . ! ==
9 AND " .&. . .


8 XOR ... .. .

7 OR ... 1...
6 AND . . .. & & . . .

5 OR . 11...
. .

4 . . . ? ...... .

3 . .. ...
=
. . . += . . .

*=
. . . /= . . .
. %=

. . . <<= . . .
. . . >>= . . .
. . . >>>= . . .
. . . &= . . .
=
. . . 1=. . .
2 yield yi eld . . .
1 . . ...
.

...'. . .

362 .

D
Accessor property, 339 Data
Accumulator, 1 69 attribute, 301
Ajax, 308 property, 339
Alternation, 276 type, 57
Anchor, 289 Declaration, 1 45
Anonymous function, 1 38 Definition, 1 45
Argument, 35; 107; 1 3 1 Dependencies, 47
Array, 73 Destructuring assignment, 1 24
Arrow notation, 140 Document, 294
Asynchronous Object Model, 294
event, 36 DOM, 294
Javascript And Xml, 308 DRY, 220
Duck typing, 1 86
Dynamic dispatch, 1 8 1
Backreference, 284
Block
scope, 1 49 EBNF, 9 5
statement, 85 Element, 295
Boilerplate, 34 Escaping, 64
Bubling, 304 Event, 241
Build tool, 39; 48 handler, 37
Evergreen, 40
Exception, 94
Callback, 1 69; 227; 232 handling, 1 97
hell, 237 Exection context, 146
Call stack, 200 Existence, 1 46
Camel case, 59 Exit code, 330
Canvas, 33 Expression, 1 05; 107
Capturing, 303
Cascading Style Sheet, 29 F
CDN, 32 Flowchart, 8 1
Chaining, 316 FOUC, 3 1 1
Character set, 278 Freezing, 344
Class, 1 77 Fnction, 1 29
method, 183 expression, 1 38
Closure, 1 52 scope, 1 54
Collision, 1 88
Comment, 28
G
Commit, 44 Garbage collection, 1 46
Condition, 84 Generator, 209
Console, 3 1 Getter, 339
Constructor, 1 77 Global scope, 147
Content Delivery Network, 32 Grouping, 281
CORS, 308

CSS, 29
Haskell Curry, 229
selector, 298
Hoisting, 1 55
Currying, 229
Primitive, 6 1
IIFE, 153 Promise, 238
Immediately Invoked Function Expression, 153 Property, 1 75
Instance, 177 attribute, 341
method, 183 Prototype, 1 8 1
Interface, 1 88 chain, 1 8 1
lterator, 205 Proxy, 346
protocol, 207 R
J Recursion, 1 39; 229
JQuery object, 3 1 5 Reference type, 1 33
JQuery-wrapped DOM elements, 3 1 4 Regex, 76
JSON, 75 Regexp, 76
Regular expression, 76; 271
Repetition, 280
, 1 75 Return value, 1 30

L s
Lexical structure, 1 46 Scope, 145
Linter, 39; 52 Sealing, 344
Litera\, 60 Set, 1 94
Lookahead, 290 Setter, 339
Lvalue, 122 Short-circuit evaluation, 1 1 7
L-, 122 Side effect, 1 17
Signature, 1 33
Snake case, 60
, 1 9 1 Sort function, 1 63
Metaprogramming, 346 Spread operator, 1 25
Metasyntax, 95 Standalone k, 149
Method, 1 35; 1 77 Statement, 1 07
Mixin, 1 88 Static method, 183
Modifier, 280 Stopping condition, 230
Multiple inheritance, 1 88 Stream, 335
Multitasking, 231 Strict mode, 1 58
String, 64
N concatenation, 66
NaN, 1 1 3 interpolation, 67
Node, 294; 3 1 9 Subc\ass, 1 77
Nul\, 69 Subexpression, 282
Subroutine, 2 1 5

Superc\ass, 1 77
Object, 35; 62 Symbo\, 69
Object-Oriented Programming, 1 77
Operand, 1 07
Operator precedence, 1 06 TDZ, 157
Template string, 67; 126

Temporal Dead Zone, 1 57
Parameter, 1 3 1 Terminal, 4 1
Parsing, 277 Ternary, 1 18
Pipe, 335 Transcompiler, 39
Pipeline, 5 1 ; 225 Transpilation, 40
Piping, 336 Traverse, 296
Polymorphism, 1 85
Preventing extension, 344

364
u
Uncaught exception, 200 , 289
Undefined, 69 , 282
Unhandled exception, 200
Unicode, 64
UTC, 254 , 75
, 1 24
v , 278
Value, 1 75 , 339
type, 1 33 , 1 8 1
Variale, 57 , 294
masking, 1 50
3
, 4 7
, 1 49 , 47
, 1 69 , 152
, 277 , 344
, 1 38 , 344
, 35; 107 , 344
, 3 3 1 , 60
, 1 3 1 , 1 75
, 36

, 301 , 59
, 341 , 39; 48
, 1 88
, 94
, 6 1 , 205

jQuery, 32
Math.js, 263 , 335
Moment.js, 255 , 229
Numeral.js, 266 , 29
Paper.js, 33 , 1 77
seedrandom.js, 268 Node, 295
Object, 1 86
finally, 202 RegExp, 272
, 85 , 1 75
-, 8 1
const, 58

let, 57; 1 54
, 59 return, 1 30
, 40 this, 1 36
, 1 30 var, 1 54
, 157 yield, 2 1 0
, 330
, 304 , 28
, 105; 1 07 , 5 1 ; 225; 336
, 1 1 7 , 66; 1 1 4
, 3 1

, 58
, 208
, 1 77
, 268

try... catch ... fina\ly, 202

365

, 146 Error, 1 97
, 60 Function, 22 1
, 69 jQuery, 3 1 5
, 1 9 1
Math, 263
, 1 50 Number, 72
, 73; 1 59 Set, 1 94
, 346 String, 72
, 95 . .
, 1 35; 1 37; 1 77 , 294
apply, 1 42 -
ind, 1 42 , 1 77
call, 1 4 1 , 145
every, 1 66 , 238
getElementByid, 298 , 1 07
getElementsByClassName, 298 , 107
getElementsByTagName, 298 break, 94
Object.keys, 1 76 continue, 94
querySelector, 298 if, 9 1
querySelectorAll, 298 if. . . else, 88
reduce, 1 68 instanceof, 1 86
some, 1 66 return, 94; 2 1 2
, 183 switch, 97
, 183 throw, 94
, 183 try".catch, 1 98
, 231 typeof, 1 2 1 ; 1 57; 1 98
, 1 88 void, 1 22
, 280 yield, 2 1 2
, 320 , 107
npm, 322
, 1 1 9
, 322 , 1 1 6
, 322 , 1 1 9
, 1 22
, 76; 1 94 , 125
, 278 , 1 1 1
, 6 1 , 1 18
, 145
, 1 53 , 76; 1 9 1
, 200
, 1 3 1
, 1 45 , 57
arguments, 1 35
, 1 49
this, 1 36
, 1 47
, 1 54 , 303
, 1 97; 1 98 , l 1 7
, 37 , 280
, 284 , 282
, 227; 232 , 2 1 5
, 296 , 1 55
, 35; 62; 70
Boolean, 72 . .
Date, 75; 253 , 185

366
, 36 , 1 33
, 335 , 1 33
, 1 88 , 39; 50
, 1 06 , 40
, 1 77
-, 346
, 320 , 294
, 207 , 290
, 1 8 1 , 84
, 230
, 1 86
, 1 1 1
-, 95
, 76; 271 , 44
, 1 39; 229 , 1 38
, 1 29; 2 1 5
, 1 69
, 1 46 , 1 63
, 175
_proto_, 1 82

, 339 , 229
, 339 , 33
CSS, 298
, 308
, 1 8 1
, 32
, 1 33
do . . . while, 89
, 69
for, 35; 90
, 24 1
for...in, 1 0 1 ; 1 76
click, 302; 303
for."of, 1 0 1 ; 206
, 1 23
while, 84
. .
, 65
, 200 , 276
, 140 11 , 208
, 1 58 , 62
, 64
, 67
, 67; 1 26 , 34
, 1 77
, 1 46
, 244; 3 1 6 , 1 77
11
HTML, 295
, 1 16 DOM 11 jQuery, 3 1 4
, 4 1 , 289

, 57

JAVASCRIPT



JavaScript.

,
, , ,
,
,


,



JavaScript.

-

,

,
- .

,


www.williamspuishing.com
JavaScript
-
.

ISBN 978-5-8459- 1 9 59-5

Оценить