JavaScript
JavaScript
14 2015 .
learn.javascript.ru.
.
- .
JavaScript
JavaScript
, !
,
, use strict
, typeof
: alert, prompt, confirm
: if, '?'
while, for
switch
,
: JavaScript
Chrome
?
chai mocha
:
:
c
:
:
arguments
,
,
[[Scope]] new Function
JavaScript
with
, this
: toString valueOf
new
,
this: call, apply
: bind
-,
: [[Class]], instanceof
JSON, toJSON
setTimeout setInterval
: eval
, try..catch
F.prototype new
JavaScript
JavaScript
: instanceof
, Error
JavaScript
.
,
JavaScript.
JavaScript .
JavaScript
, JavaScript, ,
, JavaScript.
JavaScript?
JavaScript , web- .
. HTML ,
.
JavaScript . - .
JavaScript , Java
JavaScript?
JavaScript, : LiveScript.
Java, ,
.
, JavaScript Java. ,
-, JavaScript , ,
, ECMAScript , Java
.
, ,
.
JavaScript , ,
. .
,
, , :
.
, ,
, , ,
. .
.
,
, .
(). JavaScript.
JavaScript
, , .
. JavaScript .
JavaScript,
. , , JavaScript .
, ,
, .
JavaScript
.
JavaScript?
JavaScript .
, ,
, .
, JavaScript.
JavaScript , ,
, - , :
HTML-, , , ,
..
, , ,
..
(
"AJAX").
cookie, ,
, !
JavaScript?
JavaScript ,
..
, JavaScript
- .
, JavaScript , .
, ,
,
JavaScript .
JavaScript / ,
. .
,
.
.
JavaScript, , ,
,
( , , ).
, ,
, . ,
, JavaScript .
JavaScript , .
, , .. .
JavaScript?
JavaScript:
HTML/CSS.
.
.
.
JavaScript
.
, ,
. JavaScript .
HTML 5
HTML 5 HTML, , ,
.
:
/ ( , ).
,
.
.
/, Flash.
2d 3d- , .
HTML5 ,
.
: JavaScript
.
EcmaScript 6
JavaScript . EcmaScript 5
, EcmaScript 6 .
, JavaScript,
.
: JavaScript ,
.
, HTML5 ECMAScript
.
.
, - .
, ,
, .
, ,
, , JavaScript-.
, - .
, ,
.
: .
JavaScript .
, JavaScript
, .
Java
Java , . .
Java, HTML applet,
:
<appletcode="BTApplet.class"codebase="/files/tutorial/intro/alt/">
<paramname="nodes"value="50,30,70,20,40,60,80,35,65,75,85,90">
<paramname="root"value="50">
</applet>
, Java,
. , (
), Java .
, JavaScript-, Java?
, Java- , ,
. ,
.
Java
,
.
.
Java
.
Java,
,
.
Java- HTML, .
JavaScript.
.
JavaScript (Chrome, Opera, Firefox), (ActiveX Internet Explorer).
(
, PDF), .
Java-, ,
, .
Adobe Flash
Adobe Flash - -, ,
.
Flash- , ActionScript.
HTML- .
Flash , - ,
, ,
.
, UDP P2P
Flash
.
.
: ,
, . -
.
Flash HTML, .
,
, JavaScript.
JavaScript
JavaScript : , ,
, ,
, .
,
JavaScript,
JavaScript-.
,
.
- :
CoffeeScript JavaScript,
. , Ruby.
TypeScript ,
. MicroSoft.
Dart , JavaScript, ,
,
( ). Google.
ES6 ES7
, ,
JavaScript, ,
.
, babeljs
, .
JavaScript HTML/CSS.
.
JavaScript- .
, Flash, Java, ActiveX/NPAPI
, JavaScript.
CoffeeScript, TypeScript , JavaScript
, , , , ,
JavaScript.
.
, . ,
, ,
, , .
,
.
,
JavaScript .
, .
, .
, , .
JavaScript :
1. Mozilla Developer Network , .
Firefox, .
, , :
1. http://help.dottoro.com
HTML/CSS/JavaScript.
2. http://javascript.ru/manual JavaScript ,
, .
, , . , : http://javascript.ru/RegExp.
3. http://www.quirksmode.org .
, , .
quirksmode onkeypress Google.
4. http://caniuse.com
HTML/CSS/JavaScript. , :
http://caniuse.com/#feat=cryptography .
, , ,
JavaScript, , CSS ..
- , , , ,
i.
ECMAScript
( , ) Javascript
ECMAScript .
.
"JavaScript" ?
: JavaScript JavaScript,
- ?
, JavaScript ,
Oracle.
ECMAScript ,
.
, ,
, .
HTML/DOM/CSS
JavaScript , ECMAScript .
, HTML, CSS, XML
(World Wide Consortium, W3C).
w3.org . , , ,
, .
Google .
, document.cookie document.cookie site:w3.org
dev.w3.org
, .
:
Mozilla Developer Network Firefox . Google-:
"RegExpMDN", MDN.
MSDN IE. Google-: "RegExpmsdn".
JScript: "RegExpmsdnjscript".
Safari Developer Library
Safari.
http://help.dottoro.com HTML/CSS/JavaScript
. Google-: "RegExpdottoro".
http://javascript.ru/manual JavaScript .
, , . , : http://javascript.ru/RegExp. Google-:
"RegExpsite:javascript.ru".
, :
JavaScript, ES5 ()
HTML/DOM/CSS http://w3.org
ES3 ().
Google-: "document.cookiesite:w3.org".
http://dev.w3.org
http://whatwg.org/specs/
, :
http://quirksmode.org/
Google-: "innerHeightquirksmode".
:
http://caniuse.com
Google-: "caniusegeolocation".
.
, :
1. .
2. .
3. ( . folding) - .
IDE
IDE (Integrated Development Environment) ,
, ,
, , , .
, IDE ,
, ..
IDE, .
IntelliJ: WebStorm ,
PHPStorm (PHP) , IDEA (Java) , RubyMine (Ruby) .
Visual Studio, .NET (Win)
Eclipse, Aptana
Komodo IDE
Netbeans
Zend Studio
Komodo Edit
, Visual Studio, -.
.
, JavaScript.
IDE , .
, -, ,
.
, IDE, , .
, -
.
,
IDE , , IDE
.
:
Sublime Text
SciTe
(-, shareware).
, (Windows, ).
Notepad++
(Windows, ).
Vim, Emacs. .
:
IDE Jetbrains: JavaScript WebStorm , - ,
: PHPStorm (PHP) , IDEA (Java) , RubyMine (Ruby) .
, .
Sublime Text
,
. , , -
.
, , ,
, .
, ?
, , .
,
, .
Chrome Firefox.
, ,
. , , Internet Explorer,
, Chrome/Firefox.
,
, , JavaScript.
Google Chrome
bug.html
JavaScript- . , ,
.
Ctrl+Shift+J, Mac, Cmd+Shift+J.
Console, .
:
bug.html ,
. lalala,
.
JavaScript,
alert("Hello") Enter.
.
( )
Shift+Enter.
Chrome Chrome.
Firefox
Firefox Firebug.
1. .
https://addons.mozilla.org/ru/firefox/addon/firebug/
. Firebug - :
, . Ctrl+\
.
, F12 Firebug,
, .
2. , , .
, ,
:
3. , Firebug , Firebug,
.
Firebug : bug.html.
:
.
.
Chrome, ,
, Ctrl+Enter( Mac Cmd).
.
.
, -
firebug.ru
Internet Explorer
F12.
: bug.html. Chrome/Firefox,
- , IE
Chrome/Firefox.
Safari
: Ctrl+Shift+I, Ctrl+Alt+C Mac Cmd Ctrl.
:
1. Safari .
, - .
:
"". .
2. .
, .
, ,
, .
JavaScript.
JavaScript
.
, !
, .
SCRIPT
?
( !) , JavaScript
,
, : JavaScript.
.
, :)
:
<script>...</script>
script . HTML
type, . <script>.
, <script>:
1. , script
2. script, JavaScript- ,
.
3. , HTML-
.
, .
alert()
, .
META
,
, .
, :
1. , HEAD <metacharset="utf8">.
, .
2. , UTF-8, , , windows
1251.
HTML, ,
.
SCRIPT
SCRIPT .
:
<scripttype=...>
HTML5, HTML 4 .
: type="text/javascript". type, .
type .
<scriptlanguage=...>
, . ,
JavaScript, .
HTML-
SCRIPT, Javascript , .
:
<scripttype="text/javascript"><!
...
//></script>
, , Netscape, .
.
, <script>,
.
alert
: 5
, JavaScript!.
, , , .
,
JavaScript- , HTML:
<scriptsrc="/path/to/script.js"></script>
/path/to/script.js , ( ).
.
URL, :
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.2.0/lodash.js"></script>
, src="lodash.js"
.
, :
<scriptsrc="/js/script1.js"></script>
<scriptsrc="/js/script2.js"></script>
...
:
, HTML ,
.
, ,
.
, , , ,
.
src, .
SCRIPT .
c:
<
s
c
r
i
p
t
s
r
c="file.js">
alert(1);//src,
</script>
: SCRIPT src, . :
src, , :
<scriptsrc="file.js"></script>
<script>
alert(1);
</script>
: defer/async
<script> .
, <p> :
<!DOCTYPEHTML>
<html>
<head>
<metacharset="utf8">
</head>
<body>
<p>:</p>
<script>
alert('!');
alert('!');
alert('!');
</script>
<p>!</p>
</body>
</html>
. , , .
,
.
. , ,
, . ,
,
. .
, -
.
, , , ?
.
, ( ):
<p>...</p>
<scriptsrc="https://js.cx/hello/ads.js?speed=0"></script>
<p>...!</p>
, .
, ?
, .
,
, , -
, .
, ,
. ,
, .
async defer:
async
, IE9-. . ,
<scriptasyncsrc="..."> ,
. .
defer
, IE. ,
, , async, ,
defer .
, ( async) , :
<scriptsrc="1.js"async></script>
<scriptsrc="2.js"async></script>
async defer
async defer ,
async.
async/defer
async/defer , , ..
src.
<script>...</script>,
.
async:
<p>...</p>
<
s
c
r
i
p
t
a
s
y
n
csrc="https://js.cx/hello/ads.js?speed=0"></script>
<p>...!</p>
, , alert
, .
.
<script> ,
. .
<script>,
<scriptsrc=""></script>
async defer ,
( ) .
.
async defer: defer
, async .
, - .
, , .
alert
: 5
alert
alert.js, .
, .
?
: 4
small.js big.js.
, small.js , big.js
?
<scriptsrc="big.js"></script>
<scriptsrc="small.js"></script>
?
<scriptasyncsrc="big.js"></script>
<scriptasyncsrc="small.js"></script>
?
<scriptdefersrc="big.js"></script>
<scriptdefersrc="small.js"></script>
?
: 4
.
?
<scriptdefersrc="small.js"></script>
<scriptasyncsrc="big.js"></script>
<scriptdeferasync>
alert("");
</script>
, .
: alert(',!') .
, .
, alert :
alert('');alert('');
, :
alert('');
alert('');
, .
:
alert('')
alert('')
JavaScript
.
, , !
, :
alert(3+
1
+2);
6.
, . ? ,
, JavaScript
. , , .
JavaScript ,
.
, , ,
.
, .
:
[1,2].forEach(alert)
1, 2. , .
, :
alert("")
[1,2].forEach(alert)
alert, .
JavaScript , (!).
, :
alert("");
[1,2].forEach(alert)
JavaScript . , ,
, .
.
, , .
.
JavaScript .
//.
:
//""
alert('');
alert('');//
- "/*" "*/", :
/*.
.
*/
alert('');
alert('');
. /*...*/ //
.
/*
alert('');
*/
alert('');
!
,
Ctrl+/ - Ctrl+Shift+/
( ).
.
!
:
/*
/*?!?*/
*/
alert('');
. .
, .. JavaScript,
.
,
JavaScript.
, use strict
JavaScript .
, , HTML/JS-
.
, ,
.
EcmaScript 5 (ES5),
, , ,
, .
, , ,
-. ,
, usestrict.
IE9-.
use strict
"usestrict"; 'usestrict'; .
:
"usestrict";
//ES5
...
usestrict
nousestrict , .
, .
usestrict
. , usestrict
,
.
use
strict .
use strict?
, , .
, , .
, .
IE9-, "usestrict".
, , "usestrict",
Chrome. , IE9- ! -
, , -.
IE9-, , Chrome.
, . . , (
) , "usestrict"
.
, "usestrict".
, "usestrict", ,
"usestrict".
, ,
.
, "usestrict"
.
?
usestrict , ,
.
, , , "use
strict".
ES5-shim
IE8 JavaScript, ES3.
, ,
ES5 shim , es5shim.js es5sham.js .
.
, , IE8-
ES5 shim .
JavaScript .
, ,
.
, , .
, . ,
.
, .
, .
, , var:
varmessage;
, :
varmessage;
message='Hello';//
:
varmessage;
message='Hello!';
alert(message);//
:
varmessage='Hello!';
:
varuser='John',age=25,message='Hello';
, ,
.
, message , "Hello!":
, .
:
varmessage;
message='Hello!';
message='World!';//
alert(message);
:
varhello='Helloworld!';
varmessage;
//
message=hello;
alert(hello);//Helloworld!
alert(message);//Helloworld!
:
,
. , Scala Erlang .
,
. - (
), .
, , ,
. , , ,
, . -
.
JavaScript .
1. : , , $ _
2. .
:
varmyName;
vartest123;
'$' '_'
, :
var$=1;//'$'
var_=2;//'_'
alert($+_);//3
:
var1a;//
varmyname;//''
apple AppLE .
,
, :
var="";
alert();//""
, ,
.
, ,
, : var,class,return,export .
, :
varreturn=5;//
alert(return);
var
JavaScript var,
:
num=5;//num,
"usestrict" .
:
"usestrict";
num=5;//error:numisnotdefined
, usestrict , :
varsomething;
"usestrict";//
num=5;//,
IE8- var
IE8-,
var.
IE8- , :
<divid="test"></div>
<script>
test=5;//!
alert(test);//
</script>
, . ,
, . :
varCOLOR_RED="#F00";
varCOLOR_GREEN="#0F0";
varCOLOR_BLUE="#00F";
varCOLOR_ORANGE="#FF7F00";
varcolor=COLOR_ORANGE;
alert(color);//#FF7F00
, , .
.
? varcolor="#FF7F00"?
1. -, COLOR_ORANGE . varcolor="#FF7F00"
, . , COLOR_ORANGE
#FF7F00.
2. -, , #FF7F00, ,
.
,
.
JavaScript . var.
, ,
.
: varx=10.
, _, ,
. , , .
: 2
1. : admin name.
2. name "".
3. name admin.
4. admin( ).
, .
, ,
.
, ,
( 5 , ).
, .
? , ( )
. , , -,
.. ? ?
, ,
.
1.
. .
:
varmoiTovari;
varcena;
varssilka;
:
varmyGoods;
varprice;
varlink;
?
-,
. - ,
, , .
-, , .
-, , .
, ,
, , ,
. , ,
.
.
2.
.
, , a, e, p, mg
,
.
, .
.
3.
.
:
varborderLeftWidth;
, -, camelCase.
,
'_':
varborder_left_width;
JavaScript borderLeftWidth,
. .
, c
, .. '_'.
, .
.
, ,
, , .
, ,
.
, , , , -
. , , ,
, , borderLeftWidth. , , , ,
, : leftBorderWidth.
, ,
, , .
, leftBorderWidth, , : borderLeftWidth.
? , , - ,
. , .
. ,
, , .
, .
, JavaScript,
.
,
.
, .
.
.
,
, , ,
.
, , ,
, , . ?
, .
.
, .
: 3
1. "".
.
2. "". .
, typeof
JavaScript .
, ,
.
number
varn=123;
n=12.345;
, .
Infinity() NaN( ).
, Infinity :
alert(1/0);//Infinity
NaN , :
alert(""*2);//NaN,
, , ,
.
JavaScript .
string
varstr="";
str='';
JavaScript .
.
, .
.
, char. JavaScript string. , ,
.
() boolean
: true() false().
, /, :
varchecked=true;//
checked=false;//
,
.
null
null , ,
null:
varage=null;
JavaScript null ,
. ,
.
, , age.
undefined
undefined, null, ,
. .
, , undefined:
varx;
alert(x);//"undefined"
undefined , :
varx=123;
x=undefined;
alert(x);//"undefined"
undefined , .
null.
object
5 .
: .
.
{...}, :
varuser={name:""};
, , , ,
.
typeof
typeof .
: :
1. : typeofx.
2. : typeof(x).
, .
typeof , :
typeofundefined//"undefined"
typeof0//"number"
typeoftrue//"boolean"
typeof"foo"//"string"
typeof{}//"object"
typeofnull//"object"(1)
typeoffunction(){}//"function"(2)
, typeof -.
1. typeofnull=="object" ,
. null , .
2. . ,
JavaScript, . typeof ,
"function". ,
.
,
.
, , JavaScript ,
.
+, *,
.
, ,
JavaScript.
: , ,
, .
, , , .
, . : 5*2
. : .
, . ,
"" :
varx=1;
x=x;
alert(x);//1,
, .
:
varx=1,y=3;
alert(yx);//2,
, +
'+' .
'+' , :
vara=""+"";
alert(a);//
, () .
, !
, -,
. :
alert('1'+2);//"12"
alert(2+'1');//"21"
"+".
.
:
alert(2'1');//1
alert(6/'2');//3
, +
, , :
alert(+1);//1
alert(+(12));//1
, . , .
, ,
.
, HTML- ,
.
, , , ? :
varapples="2";
varoranges="3";
alert(apples+oranges);//"23",
, :
varapples="2";
varoranges="3";
alert(+apples++oranges);//5,,
.
: ,
, '+' .
? ,
.
,
.
, 2*2+1 , ..
, . JavaScript
, .
, , .
. , .
, .
:
15
15
14
14
13
13
15, , 13 ,
+apples++oranges apples oranges, .
, =.
: 3.
, - , , x=2*2+1
, =.
varx=2*2+1;
alert(x);//5
:
vara,b,c;
a=b=c=2+2;
alert(a);//4
alert(b);//4
alert(c);//4
-,
2+2, c, b=c, , a=b.
"="
. x= .
x, .
:
vara=1;
varb=2;
varc=3(a=b+1);
alert(a);//3
alert(c);//0
%
% , , ,
.
a%b a b.
:
alert(5%2);//1,52
alert(8%3);//2,83
alert(6%3);//0,63
/: ++, - JavaScript, ,
.
:
++ 1:
vari=2;
i++;//i=i+1.
alert(i);//3
1:
vari=2;
i;//i=i1.
alert(i);//1
:
/ . 5++ .
, : i++(
) ++i( ).
: 1.
, . ,
/ , .
:
vari=1;
vara=++i;//(*)
l
e
r
t
(
a
)
;
/
/
2
(*) ++i , a. a
i .
i++ ++i, ,
.
a i, 1:
vari=1;
vara=i++;//(*)
l
e
r
t
(
a
)
;
/
/
1
, /
, :
vari=0;
i++;
++i;
alert(i);//2
, :
vari=0;
alert(++i);//1
, :
vari=0;
alert(i++);//0
/
,
:
vari=1;
alert(2*++i);//4
vari=1;
alert(2*i++);//2,
, ,
i++,
, .
, , :
vari=1;
alert(2*i);
i++;
32-
.
- JavaScript,
.
:
AND() ( &)
OR() ( |)
XOR( ) ( ^)
NOT() ( ~)
LEFT SHIFT( ) ( <<)
, :
varn=2;
n=n+5;
n=n*2;
, :
varn=2;
n+=5;//n=7(n=n+5)
n*=2;//n=14(n=n*2)
alert(n);//14
+,,*,/ <<,>>,>>>,&,|,^.
, ,
:
varn=2;
n*=3+5;
alert(n);//16(n=2*8)
','.
, :
a=(5,6);
alert(a);
, ','.
, , .
, . a=
(5,6) , '='
',', (a=5),6.
,
, ?
,
. :
//
o
r
(
a
=
1
,
b
=
3
,
c
=
a
*
b
;a<10;a++){
f
...
}
JavaScript- .
,
: 5
, , ?
vara=1,b=1,c,d;
c=++a;alert(c);//2
d=b++;alert(d);//1
c=(2+++a);alert(c);//5
d=(2+b++);alert(d);//4
alert(a);//3
alert(b);//3
: 3
x ?
vara=2;
varx=1+(a*=2);
,
.
:
/: a>b, a<b.
/ : a>=b, a<=b.
a==b. '='. a=b
.
. , JavaScript
!=.
, . .
:
true , , .
false , , .
:
alert(2>1);//true,
alert(2==1);//false,
alert(2!=1);//true
, ,
:
vara=true;//
varb=3>4;//
alert(b);//false
alert(a==b);//(true==false),false
:
alert(''>'');//true
, Unicode!
,
(). JavaScript Unicode .
. , , ,
.
Unicode , .
:
alert(''>'');//true,
,
. , , ,
.
, , .
:
,
:
alert(''>'');
. :
alert(''>'');//true,..''>''
:
alert(''>'');//true,''"".
:
. , prompt
, .
, , , .
:
alert("2">"14");//true,,214
2 14, ,
'2' '1'.
. ,
+:
alert(+"2">+"14");//false,
, .
.
:
alert('2'>1);//true,2>1
alert('01'==1);//true,1==1
alert(false==0);//true,false0
alert(true==1);//true,true1.
,
.
== " 0 false:
alert(0==false);//true
:
alert(''==false);//true
, .
, false, 0.
, 0 false?
===( ) !==.
, false:
alert(0===false);//false,..
, , .
null undefined
,
><<=>=, , null/undefined.
, null/undefined , .
-.
1. null undefined == .
.
2. null 0, undefined NaN.
.
null 0
null :
alert(null>0);//false
alert(null==0);//false
, , null .
l
e
r
t
(
n
u
l
l
>
=
0
)
;
/
/
t
r
u
e
? , , ,
. .
, == >=><<= -.
, . null
undefined : , - .
,
.
undefined
undefined :
alert(undefined>0);//false(1)
alert(undefined<0);//false(2)
alert(undefined==0);//false(3)
32 (
). , ,
32 () .
,
, ,
.
32-
JavaScript 32-
.
32- ,
.
, ,
.
, , , .
, 32 .
(
). , ,
.
:
a=0;//00000000000000000000000000000000
a=1;//00000000000000000000000000000001
a=2;//00000000000000000000000000000010
a=3;//00000000000000000000000000000011
a=255;//00000000000000000000000011111111
, 32-.
.
, (, 5 5)
1.
, , 1.
, .
, 314:
00000000000000000000000100111010
314, : 0 1, 1 0:
11111111111111111111111011000101
,
: 11111111111111111111111011000101+1=11111111111111111111111011000110.
, :
314=11111111111111111111111011000110
:
- 0 , 1 .
.
.
.
(AND)
a&b
1 ,
1.
(OR)
a|b
1 ,
1.
(XOR)
a^b
1 ,
1 ( ).
(NOT)
~a
a<<b
a>>b
a>>>b
a b ,
.
a b ,
.
a b ,
.
:
1. 32- ,
. , , .
2.
: , ..
, .
3. .
, , .
parseInt, toString
, -
, .
parseInt("11000",2) .
n.toString(2) n 2- .
:
varaccess=parseInt("11000",2);//
alert(access);//24,2
varaccess2=access.toString(2);//
alert(access2);//11000
.
.
& ( )
.
a&b a b .
&:
a&b
:
9(.10)
=00000000000000000000000000001001(.2)
14(.10)
=00000000000000000000000000001110(.2)
14&9(.10)
=00000000000000000000000000001000(.2)
=8(.10)
| ( )
. a|b 1,
a,b 1.
|:
a|b
:
9(.10)
=00000000000000000000000000001001(.2)
14(.10)
=00000000000000000000000000001110(.2)
14|9(.10)
=00000000000000000000000000001111(.2)
=15(.10)
^ ( )
.
a b 1, a=1 b=1, a=b=1.
:
a^b
, 1, 1, 1, .
.
:
9(.10)
=00000000000000000000000000001001(.2)
14(.10)
=00000000000000000000000000001110(.2)
14^9(.10)
=00000000000000000000000000000111(.2)
=7(.10)
,
. .
, : a^b^b==a.
data.
,
.
key.
:
data data^key.
data , key, ^
. JavaScript ^ 32- , data
.
data^key , .
, data 9, key 1220461917.
:9
00000000000000000000000000001001
:1220461917
01001000101111101100010101011101
9^key:
01001000101111101100010101010100
10():
1220461908
, 1220461908,
^key.
data.
:
:
9^key=1220461908
01001000101111101100010101010100
:1220461917:
01001000101111101100010101011101
1220461917^key:
00000000000000000000000000001001
10():
9
, ,
XOR ^
.
~ ( )
, .
:
~a
:
9(.10)
=00000000000000000000000000001001(.2)
~9(.10)
=11111111111111111111111111110110(.2)
=10(.10)
- , ~n==(n+1).
:
alert(~3);//4
alert(~1);//0
<< ( )
. ,
, .
<< .
, .
, 9<<2 36:
9(.10)
=00000000000000000000000000001001(.2)
9<<2(.10)
=00000000000000000000000000100100(.2)
=36(.10)
<<2 .
2
<<N , N, :
alert(3<<1);//6,2
alert(3<<2);//12,2
alert(3<<3);//24,2
, , 32-
, :
alert(10000000000<<1);//1474836480,
alert(10000000000*2);//20000000000,
>> ( , )
, .
- .
( - ) , , .
.
, 9>>2 2:
9(.10)
=00000000000000000000000000001001(.2)
9>>2(.10)
=00000000000000000000000000000010(.2)
=2(.10)
>>2 01
00.
, 9>>2 3:
9(.10)
=11111111111111111111111111110111(.2)
9>>2(.10)
=11111111111111111111111111111101(.2)=3(.10)
>>2 11
11. , , - () 1.
2
>>N , N:
alert(100>>1);//50,2
alert(100>>2);//25,2
alert(100>>3);//12,2,
>>> ( )
. .
.
0, .
>>>
>> , . .
. , 9>>>2 1073741821,
9>>2( 3):
9(.10)
=11111111111111111111111111110111(.2)
9>>>2(.10)
=00111111111111111111111111111101(.2)
=1073741821(.10)
, .
, ,
JavaScript.
, !
JavaScript ^, &, | ==.
, a==b^0 a==b,
^0, (a==b)^0.
, . ,
: a==(b^0).
, .
:
.
, , ,
.
- :
1, 0, :
10-
= 20
= 30
= 31
, ,
.
, 10100=20.
.
, ,
, !
, 2- .
, : 00001(=1)( 1 ,
).
, : 00010(=2).
, : 00100(=4).
, : 01000(=8).
, : 10000(=16).
1
, access=11000.
, :
varACCESS_ADMIN=1;//00001
varACCESS_GOODS_EDIT=2;//00010
varACCESS_GOODS_VIEW=4;//00100
varACCESS_ARTICLE_EDIT=8;//01000
varACCESS_ARTICLE_VIEW=16;//10000
|.
varguest=ACCESS_ARTICLE_VIEW|ACCESS_GOODS_VIEW;//10100
vareditor=guest|ACCESS_ARTICLE_EDIT|ACCESS_GOODS_EDIT;//11110
varadmin=editor|ACCESS_ADMIN;//11111
, , editor ,
(&) .
, :
alert(editor&ACCESS_ADMIN);//0,
alert(editor&ACCESS_ARTICLE_EDIT);//8,
, 1 ,
1.
.
, , .
1 , 00110(=6 10- ).
varcheck=ACCESS_GOODS_VIEW|ACCESS_GOODS_EDIT;//6,00110
alert(admin&check);//0,
(check ),
.
.
, , , ..
.
:
//
findUsers(ACCESS_GOODS_EDIT|ACCESS_ADMIN);
- , , ,
. , JavaScript 32-
, , , 33 .
, ,
true/false.
, ,
, JavaScript (3d-),
( JavaScript), ,
, .
,
. , .
, (~):
alert(~~12.345);//12
(^) :
alert(12.345^0);//12
, :
l
e
r
t
(
1
2
.
3
*
1
4
.
5
^
0
)
;
/
/
(
=
1
7
8
)
"
1
2
.
3
1
4
.
5
"
a
, :
alert(1.1+1.2^0);//2,
-1
32- ,
() 1.
(~). , n=~n
+1. , : ~n=(n+1).
, ~n==0 n==1.
n==1:
varn=5;
if(~n){//,..~n=(5+1)=6
alert("n1");//!
}
varn=1;
if(~n){//,..~n=(1+1)=0
alert("......");
}
1, , .
str.indexOf("") str, 1 .
varstr="";
if(~str.indexOf("")){//"if(~...indexOf)"""
alert('!');
}
2
a<<b, , a 2 b.
:
alert(1<<2);//1*(2*2)=4
alert(1<<3);//1*(2*2*2)=8
alert(3<<3);//3*(2*2*2)=24
, ,
, 32- ,
64 .
a>>b,
a 2b.
alert(8>>2);//2=8/4,2
alert(11>>2);//2,()
: &|^<<>>>>>.
: ~.
, :
: (12.34^0)=12.
1: if(~n){n1}.
() .
&.
, .
: 5
? ?
alert(123^0);//123
alert(0^123);//123
alert(~~123);//123
,
: 3
isInteger(num), true, num , false.
:
alert(isInteger(1));//true
alert(isInteger(1.5));//false
alert(isInteger(0.5));//false
^, |, &?
: 5
, a b ?
a^b==b^a
a&b==b&a
a|b==b|a
, ?
?
: 5
alert' ?
alert(123456789^0);//123456789
alert(12345678912345^0);//1942903641
alert
:
alert()
alert ,
.
alert("");
, , . ,
, ..,
. OK.
prompt
prompt :
result=prompt(title,default);
title, ,
default OK/CANCEL.
- OK, CANCEL
Esc .
prompt , null,
.
alert, prompt.
varyears=prompt('?',100);
alert(''+years+'!')
default
. IE
"undefined".
IE, :
vartest=prompt("");
:
vartest=prompt("",'');//<
confirm
:
result=confirm(question);
, ,
. .
, , , .
, ,
, , .
.
, , .
alert .
prompt , ,
null, (CANCEL/ Esc).
confirm , OK CANCEL
true/false.
: 4
, .
: if, '?'
, , .
if.
:
varyear=prompt('ECMA2625.1?','');
if(year!=2011)alert('!');
if
if() , year!=2011. ,
true, .
:
if(year!=2011){
alert('..');
alert('..!');
}
, .
.
if(...) .
:
0, "", null undefined, NaN false,
true.
, :
if(0){//0false
...
}
:
if(1){//1true
...
}
, ,
:
varcond=(year!=2011);//true/false
if(cond){
...
}
, else
else() , :
varyear=prompt('ECMA2625.1','');
if(year==2011){
alert('!');
}else{
alert('!');//,2011
}
, else if
. elseif....
:
varyear=prompt('ECMA2625.1?','');
if(year<2011){
alert('..');
}elseif(year>2011){
alert('..');
}else{
alert(',!');
}
JavaScript ,
, else.
'?'
. :
varaccess;
varage=prompt('?','');
if(age>14){
access=true;
}else{
access=false;
}
alert(access);
'?' .
:
?1:2
, 1, 2,
:
access=(age>14)?true:false;
'?' , ,
:
access=age>14?true:false;
. .
:
'?', ..
true/false:
access=age>14;
, ,
-. .
'?'
'?'
, .
:
varage=prompt('?',18);
varmessage=(age<3)?',!':
(age<18)?'!':
(age<100)?'!':
'!';
alert(message);
, . , ,
, !
age<3, ',!',
age<18. '!',
age<100 '!' , , '
!'.
if..else:
if(age<3){
message=',!';
}elseif(a<18){
message='!';
}elseif(age<100){
message='!';
}else{
message='!';
}
'?'
'?' if:
varcompany=prompt('JavaScript?','');
(company=='Netscape')?
alert(','):alert('');
: , ,
'?'.
, (, alert
).
.
, if, .
, , if:
varcompany=prompt('JavaScript?','');
if(company=='Netscape'){
alert(',');
}else{
alert('');
}
, ,
, . , ,
, if '?'.
'?' , . ,
, if.
if ( )
: 5
alert?
if("0"){
alert('');
}
: 2
if..else, , :
JavaScript?.
EcmaScript, !, -
? EcmaScript!.
-:
: 2
if..else, , prompt,
alert:
1, ,
1, ,
0, .
: 3
, (prompt).
, , (escape)
, - .
. , !,
, .
-:
if. .
'if' '?'
: 5
if '?':
if(a+b<4){
result='';
}else{
result='';
}
'if..else' '?'
: 5
if..else '?'.
.
varmessage;
if(login==''){
message='';
}elseif(login==''){
message='';
}elseif(login==''){
message='';
}else{
message='';
}
JavaScript ||(), &&() !().
, JavaScript
.
|| ()
:
result=a||b;
:
true, true, false. JavaScript, ,
, .
:
alert(true||true);//true
alert(false||true);//true
alert(true||false);//true
alert(false||false);//false
. ,
1 true, 0 false:
if(1||0){//if(true||false)
alert('');
}
if, ,
, :
varhour=9;
if(hour<10||hour>18){
alert('1018');
}
:
varhour=12,
isWeekend=true;
if(hour<10||hour>18||isWeekend){
alert('1018');
}
JavaScript . , ,
.
, : a||b||c||.... true,
true( true),
.
, , ,
, .
x :
varx;
r
u
e
||(x=1);
t
alert(x);//undefined,x
false, ,
:
varx;
a
l
s
e
||(x=1);
f
alert(x);//1
||,
&&.
,
JavaScript
, , ,
true.
, . ,
.
:
alert(1||0);//1
alert(true||'');//true
alert(null||1);//1
alert(undefined||0);//0
, , :
varundef;//,..undefined
varzero=0;
varemptyStr="";
varmsg="!";
varresult=undef||zero||emptyStr||msg||0;
alert(result);//"!",true
, || :
alert(undefined||''||false||0);//0
, || ,
.
, || .
&& ()
&&:
result=a&&b;
true, ,
false:
alert(true&&true);//true
alert(false&&true);//false
alert(true&&false);//false
alert(false&&false);//false
c if:
varhour=12,
minute=30;
if(hour==12&&minute==30){
alert('12:30');
}
, :
if(1&&0){//true&&false
alert(',..');
}
, -, .
false, .
.
:
//true,
//
alert(1&&0);//0
alert(1&&5);//5
//false,
//,
alert(null&&5);//null
alert(0&&"");//0
, (
), :
alert(1&&2&&null&&3);//null
alert(1&&2&&3);//3
, && ,
.
, && .
&&, ||
&&, ||, .
: 1&&0=0, .
alert(5||1&&0);//5
&& if
&& if, :
varx=1;
(x>0)&&alert('');
&& , .
, alert, true.
:
varx=1;
if(x>0){
alert('');
}
, , if . ,
. , ,
.
! ()
. . :
varresult=!value;
!:
1. true/false.
2. .
:
alert(!true);//false
alert(!0);//true
, :
alert(!!"");//true
alert(!!null);//false
alert ()?
: 5
?
alert(null||2||undefined);
alert ()?
: 3
?
alert(alert(1)||2||alert(3));
alert ()?
: 5
?
alert(1&&null&&2);
alert ()?
: 3
?
alert(alert(1)&&alert(2));
?
: 5
?
alert(null||2&&3||4);
if
: 3
if , age 14 90
.
, , age 14
90.
if
: 3
if , age 14 90 .
: !,
.
if
: 5
if, .. ?
if(...)?
if(1||0)alert('');
if(1&&0)alert('');
if(null||1&&1)alert('');
JavaScript , .
.
:
1. C .
2. .
3. .
,
.
, - .
, alert.
vara=true;
alert(a);//"true"
String(val):
alert(String(null)==="null");//true
, ,
: false "false", null "null", undefined "undefined" ..
"+", .
, :
alert(true+"test");//"truetest"
alert("123"+undefined);//"123undefined"
,
( ===, !==).
Number(val), , ,
"+":
vara=+"123";//123
vara=Number("123");//123,
undefined
NaN
null
true/
false
1/0
.
, , 0, ,
NaN.
:
//"123"
alert(+"\n123\n\n");//123
:
:
alert(+true);//1
alert(+false);//0
alert("\n0"==0);//true
"\n" , :
, "", 0.
:
alert("\n"==false);
alert("1"==true);
"==" .
0, 1.
.
, null/undefined ,
.
:
undefined
NaN
null
>>=<<=,
==.
( 11.9.3 ). , null undefined "==" ,
.
.
, null : null>=0,
:
alert(null>=0);//true,..null0
alert(null>0);//false(),..null0
alert(null==0);//false(!),..==null.
undefined :
alert(undefined>0);//false,..undefined>NaN
alert(undefined==0);//false,..undefined()
alert(undefined<0);//false,..undefined>NaN
>>=<<=.
- .
true/false , if(value),
.
, , false. : 0, , null,
undefined NaN.
, true.
:
undefined, null
false
true
!!value
Boolean(value).
: "0" true
( PHP), "0" JavaScript true,
:
alert(!!"0");//true
alert(!!"");//,true!
, .
, true, false.
, , :
alert(0=="\n0\n");//true
false, true:
if("\n0\n"){
alert("true,0!");
}
JavaScript .
, if , .
JavaScript :
1. : String(value) .
.
2. : Number(value) , +value.
, .
3. : Boolean(value) , :
!!value.
.
null undefined. ,
, .
,
: 5
, . .
.
""+1+0""1+0
true+false
6/"3"
"2"*"3"
4+5+"px"
"$"+4+5
"4"2
"4px"2
7/0
"9\n"+5"9\n"5
5&&2
2&&5
5||0
0||5
null+1
undefined+1
null=="\n0\n"
+null==+"\n0\n"
while, for
.
, . 1 10
.
.
while
while :
while(){
//,
}
.
, i i<3:
vari=0;
while(i<3){
alert(i);
i++;
}
- .
.
i++ , ( ) . ,
.
:
while(true){
//...
}
, while(i!=0)
while(i):
vari=3;
while(i){//i,0,false
alert(i);
i;
}
do..while
, do..while:
do{
//
}while();
, , , , .
:
vari=0;
do{
alert(i);
i++;
}while(i<3);
do..while , .. while
, .
for
for. :
for(;;){
//......
}
, alert(i) i 0 2 ( 3):
vari;
for(i=0;i<3;i++){
alert(i);
}
:
: i=0.
: i<3.
: i++.
: alert(i), .. ( , )
:
1. : i=0 - , .
2. : i<3 , ,
.
3. : alert(i).
4. : i++ , .
5. 2.
, , : ( ) (
) , .
:
:
f
o
r
(
v
a
ri=0;i<3;i++){
alert(i);//0,1,2
}
, , i
3.
for
for .
, . :
vari=0;
for(;i<3;i++){
alert(i);//0,1,2
}
vari=0;
for(;i<3;){
alert(i);
//while(i<3)
}
, :
for(;;){
//
}
; ,
.
for..in
for..in .
, .
: break
, , .
break.
, ,
, :
varsum=0;
while(true){
varvalue=+prompt("",'');
if(!value)break;//(*)
sum+=value;
}
alert(':'+sum);
break (*), ,
, alert.
, + break , ,
, - , .
: continue
continue .
break: ,
, .
, , .
, continue, :
for(vari=0;i<10;i++){
f
(
i
%
2
=
=
0
)
c
o
n
t
i
n
u
e
;
i
alert(i);
}
i continue,
for.
continue
, , :
for(vari=0;i<10;i++){
if(i%2){
alert(i);
}
}
. , continue
if. ,
. if , ,
continue.
break/continue '?'
if '?'.
, :
if(){
a();
}else{
b();
}
:
?a():b();
a() b().
, '?',
, .
, ,
'?'.
, , break/continue.
:
i
>
5
)
?
a
l
e
r
t
(
i
)
:
c
o
n
t
i
n
u
e
;
(
, , '?'
. ,
if.
break/continue
.
, i j,
:
o
u
t
e
r
:for(vari=0;i<3;i++){
for(varj=0;j<3;j++){
varinput=prompt(''+i+','+j,'');
//
//
f
(
!
i
n
p
u
t
)
b
r
e
a
k
o
u
t
e
r
;//(*)
i
}
}
alert('!');
.
":", . , :
outer:for(vari=0;i<3;i++){...}
:
outer:
for(vari=0;i<3;i++){...}
breakouter .
,
alert.
continue ,
.
JavaScript :
while .
do..while .
for , .
, while(true). ,
, break.
,
continue.
, .
break/continue .
, , JavaScript
.
: 3
? ?
vari=3;
while(i){
alert(i);
}
i while?
: 4
, . .
1.
vari=0;
while(++i<5)alert(i);
2.
vari=0;
while(i++<5)alert(i);
i for?
: 4
, . .
1. :
for(vari=0;i<5;i++)alert(i);
2. :
for(vari=0;i<5;++i)alert(i);
: 5
for 2 10.
for while
: 5
, for while, .
for(vari=0;i<3;i++){
alert(""+i+"!");
}
,
: 5
, prompt , 100.
, .
, 100,
Cancel (ESC).
, ,
.
: 3
, 1, , , 1.
, n>1 , 2 n1 .
, 2 10.
: 2,3,5,7.
P.S. .
switch
switch if.
.
:
switch(x){
case'value1'://if(x==='value1')
...
[break]
case'value2'://if(x==='value2')
...
[break]
default:
...
[break]
}
x value1, value2
.
switch
case , break( switch).
case c ( ) default.
case switch.
switch( ):
vara=2+2;
switch(a){
case3:
alert('');
break;
case4:
alert('!');
break;
case5:
alert('');
break;
default:
alert('');
}
switch a case.
3, 4. , ,
alert('!') , break, .
break, case,
.
break:
vara=2+2;
switch(a){
case3:
alert('');
case4:
alert('!');
case5:
alert('');
default:
alert('');
}
alert:
alert('!');
alert('');
alert('');
case , .
:
vara=1;
varb=0;
switch(a){
caseb+1:
alert(1);
break;
default:
alert(',')
}
case
case .
case3 case5 :
vara=2+2;
switch(a){
case4:
alert('!');
break;
case3://(*)
case5://(**)
alert('!');
alert(',.');
break;
default:
alert(',');
}
.
vararg=prompt("arg?")
switch(arg){
case'0':
case'1':
alert('');
case'2':
alert('');
break;
case3:
alert('');
default:
alert(':'+arg)
}
0? 1? 2? 3?
, , switch
0 alert, break
alert(''). , alert.
1 .
2, switch case'2', alert('').
3, switch default. , prompt '3',
. . switch ===,
.
if, switch
: 5
if..else, switch:
switch(browser){
case'IE':
alert(',IE!');
break;
case'Chrome':
case'Firefox':
case'Safari':
case'Opera':
alert(',');
break;
default:
alert(',!');
}
if' switch
: 4
switch:
vara=+prompt('a?','');
if(a==0){
alert(0);
}
if(a==1){
alert(1);
}
if(a==2||a==3){
alert('2,3');
}
.
, ,
, -.
, .
.
alert(message), prompt(message,default)
confirm(question). .
:
functionshowMessage(){
alert('!');
}
function, ,
( ) , .
, :
functionshowMessage(){
alert('!');
}
showMessage();
showMessage();
. :
.
: , .
, var.
:
functionshowMessage(){
varmessage=',!';//
alert(message);
}
showMessage();//',!'
alert(message);//<,..
f
o
r
(
v
a
ri=0;i<3;i++){
a
r
j=i*2;
v
}
alert(i);//i=3,i,
alert(j);//j=4,j,
}
, .
.
, :
functioncount(){
vari,j;//var
for(i=0;i<3;i++){
j=i*2;
}
alert(i);//i=3
alert(j);//j=4
}
, :
a
r
u
s
e
r
N
a
m
e
='';
v
functionshowMessage(){
v
a
r
m
e
s
s
a
g
e
=
'
'
+
u
s
e
r
N
a
m
e;
alert(message);
}
showMessage();//,
, . , ,
:
varuserName='';
functionshowMessage(){
userName='';//(1)
varmessage=','+userName;
alert(message);
}
showMessage();
alert(userName);//,
, , (1), var
userName, , .
, , .
userName .
,
,
.
: !
JavaScript
.
:
functionshowMessage(){
message='';//var!
}
showMessage();
alert(message);//
message , . ,
var.
usestrict ,
, , .
.
, ,
,
.
var ,
, . , ,
.
, JavaScript, ,
, .
, .
, :
f
u
n
c
t
i
o
n
s
h
o
w
M
e
s
s
a
g
e
(
f
r
o
m
,
t
e
x
t){//from,text
from="**"+from+"**";//
alert(from+':'+text);
}
showMessage('','!');
showMessage('','?');
.
, from,
. :
functionshowMessage(from,text){
from='**'+from+'**';//from
alert(from+':'+text);
}
varfrom="";
showMessage(from,"");
alert(from);//from,
.
undefined.
, showMessage(from,text)
:
showMessage("");
,
:
functionshowMessage(from,text){
if(text===undefined){
text='';
}
alert(from+":"+text);
}
showMessage("","!");//:!
showMessage("");//:
, ,
.
, , , ,
, :
1. , undefined,
. .
2. ||:
functionshowMessage(from,text){
text=text||'';
...
}
, , , 0,
, false.
, , showMessage("","",1,2,3),
. , ,
arguments,
arguments.
, .
, calcD,
b24ac:
functioncalcD(a,b,c){
e
t
u
r
n
b*b4*a*c;
r
}
vartest=calcD(4,2,1);
alert(test);//20
return.
.
.
return , :
functioncheckAge(age){
if(age>18){
returntrue;
}else{
returnconfirm('?');
}
}
varage=prompt('?');
if(checkAge(age)){
alert('');
}else{
alert('');
}
return ,
.
:
functionshowMovie(age){
if(!checkAge(age)){
return;
}
alert("");//(*)
//...
}
, if, (*) ,
return .
return return
, return ,
undefined:
functiondoNothing(){/**/}
alert(doNothing());//undefined
, . undefined.
, return :
functiondoNothing(){
return;
}
alert(doNothing()===undefined);//true
, .
, .. .
, , ,
.
, "show" - :
showMessage(..)//show,""
, "get" , ..:
getAge(..)//get,""
calcD(..)//calc,""
createForm(..)//create,""
checkPermission(..)//check,"",true/false
, ,
, ,
.
, .
.
? , .
,
, .
, (, "validate")
. .
, , .
, jQuery $, Prototype $$,
LoDash
_.
:
function(,,){
.
.
var.
return....
return .
return; , return,
undefined.
, , :
.
, ,
,
.
:
, . ,
, .
, , , .
.
.
else?
: 4
true, age 18.
confirm .
functioncheckAge(age){
if(age>18){
returntrue;
}else{
//...
returnconfirm('?');
}
}
- , else?
functioncheckAge(age){
if(age>18){
returntrue;
}
//...
returnconfirm('?');
}
, '?' '||'
: 4
true, age 18.
confirm .
functioncheckAge(age){
if(age>18){
returntrue;
}else{
returnconfirm('?');
}
}
, , if, .
checkAge:
1. '?'
2. ||
min
: 1
Hello World :)
min(a,b), a,b.
:
min(2,5)==2
min(3,1)==1
min(1,1)==1
pow(x,n)
: 4
pow(x,n), x n. , x n
.
pow(3,2)=3*3=9
pow(3,3)=3*3*3=27
pow(1,100)=1*1*...*1=1
, x n, pow(x,n).
P.S. n, .. 1
.
JavaScript , .
, , :
functionsayHi(){
alert("");
}
alert(sayHi);//
, sayHi . ,
, .
:
functionsayHi(){//(1)
alert("");
}
varfunc=sayHi;//(2)
func();////(3)
sayHi=null;
sayHi();//(4)
1. (1)
sayHi
2. (2) func. :
sayHi . , varfunc=sayHi() func
sayHi()(, ? , undefined, sayHi return).
3. (3) sayHi() func()
4. , . ,
, (4) .
, , .
.
(), ,
.
Function Expression
,
, .
Function Expression ( ) :
varf=function(){
//
};
:
varsayHi=function(person){
alert(","+person);
};
sayHi('');
Function Declaration
, , function
(){...}, Function Declaration.
Function Declaration , .
Function Expression - ,
.
, :
//FunctionDeclaration
functionsum(a,b){
returna+b;
}
//FunctionExpression
varsum=function(a,b){
returna+b;
}
: sum,
sum.
: , Function Declaration,
.
, :
sayHi("");//,
functionsayHi(name){
alert(","+name);
}
Function Expression, :
sayHi("");//!
varsayHi=function(name){
alert(","+name);
}
Function Declaration
.
, , , sayHi-:
varage=+prompt("?",20);
if(age>=18){
functionsayHi(){
alert('!');
}
}else{
functionsayHi(){
alert('18');
}
}
sayHi();
20 , Firefox, ,
. "18", , age=20.
? , .
1. Function Declaration .
. .
2. , , Function Declaration (
). :
functionsayHi(){
alert('!');
}
functionsayHi(){
alert('18');
}
varage=20;
if(age>=18){
/**/
}else{
/**/
}
sayHi();//"18",
, if . - ,
, .
.
, , , Firefox.
: Function Declaration .
, Function Expression?
varage=prompt('?');
varsayHi;
if(age>=18){
sayHi=function(){
alert('!');
}
}else{
sayHi=function(){
alert('18');
}
}
sayHi();
varage=prompt('?');
varsayHi=(age>=18)?
function(){alert('!');}:
function(){alert('18');};
sayHi();
, , ,
, .
.
ask(question,yes,no)
f.
question, ,
yes no:
functionask(question,yes,no){
if(confirm(question))yes()
elseno();
}
functionshowOk(){
alert(".");
}
functionshowCancel(){
alert(".");
}
//
ask("?",showOk,showCancel);
- , ? , , ask?
,
confirm,
. .
, :
functionask(question,yes,no){
if(confirm(question))yes()
elseno();
}
ask(
"?",
function(){alert(".");},
function(){alert(".");}
);
ask(...), .
, ,
.
, ,
? , .
, JavaScript.
new Function
, ,
.
, :
varsum=newFunction('a,b','returna+b;');
varresult=sum(1,2);
alert(result);//3
, newFunction(params,code):
params
.
code
.
,
, .
JavaScript,
, .
JavaScript . , ,
.
, Function Declaration.
, Function Expression.
:
Function Declaration
Function Expression
(.. )
if
Function Expression. -,
, , varfunc=function(),
.
Function Expression Function
Declaration.
:
//FunctionExpression
varf=function(){...}
//FunctionDeclaration
functionf(){...}
Function Declaration .
, .
Function Expression , .
,
.
. .
,
.
.
, JavaScript.
,
, .
,
, .
pow(x, n)
x n.
:
pow(x,n)=x*pow(x,n1)
, xn=x*xn1.
, pow(2,4), :
1. pow(2,4)=2*pow(2,3)
2. pow(2,3)=2*pow(2,2)
3. pow(2,2)=2*pow(2,1)
4. pow(2,1)=2
1 pow(2,3), 2, pow(2,2),
3, 4, , ,
1 .
, 4, 3, pow(2,2)
2 1 .
JavaScript:
functionpow(x,n){
if(n!=1){//n!=1,pow(x,n)pow(x,n1)
returnx*pow(x,n1);
}else{
returnx;
}
}
alert(pow(2,3));//8
, pow n==1.
, .
1.
. ,
n.
, 10000
, .
, , ,
, , .
,
, . ,
, .
(execution context).
,
. ,
.
, pow(2,3) ,
x=2,n=3. :
:{x:2,n:3,1}
pow . n!=1 true,
n=3. if:
functionpow(x,n){
if(n!=1){//n!=1pow(x,n)pow(x,n1)
returnx*pow(x,n1);
}else{
returnx;
}
}
x*pow(x,n1), pow
.
JavaScript
.
.
pow, .
.
, ,
.
, (*):
functionpow(x,n){
if(n!=1){//n!=1pow(..n)pow(..n1)
returnx*pow(x,n1);
}else{
returnx;
}
}
alert(pow(2,3));//(*)
pow(2,3)
pow, x=2, n=3. ,
:
:{x:2,n:3,1}
, 3.
pow(2,2)
3 pow x=2, n=2.
, ( ):
:{x:2,n:3,3}
:{x:2,n:2,1}
, , ,
.
, , ,
.
pow(2,1)
3, x=2, n=1.
, :
:{x:2,n:3,3}
:{x:2,n:2,3}
:{x:2,n:1,1}
.
pow(2,1).
pow(2,1), , n!=1
false, if..else:
functionpow(x,n){
if(n!=1){
returnx*pow(x,n1);
}else{
returnx;//
}
}
, , 2.
, :
:{x:2,n:3,3}
:{x:2,n:2,3}
pow(2,2).
pow(2,2).
pow(2,2) , 4.
:
:{x:2,n:3,3}
pow(2,3).
pow(2,3).
, : pow(2,3)=8.
: 3.
, ,
.
.
, ,
n n .
:
functionpow(x,n){
varresult=x;
for(vari=1;i<n;i++){
result*=x;
}
returnresult;
}
pow , i
result.
. ,
.
, ,
, , .
, , .
.
( ),
,
HTML-, .
, JavaScript.
, , ,
Chrome,
.
.
: 5
sumTo(n), n 1 n, :
sumTo(1)=1
sumTo(2)=2+1=3
sumTo(3)=3+2+1=6
sumTo(4)=4+3+2+1=10
...
sumTo(100)=100+99+...+2+1=5050
:
1. .
2. , .. sumTo(n)=n+sumTo(n1) n>1.
3.
:
functionsumTo(n){/*......*/}
alert(sumTo(100));//5050
? ? ?
sumTo(100000)? , ?
: 4
, ,
, . n!
:
n!=n*(n1)*(n2)*...*1
n:
1!=1
2!=2*1=2
3!=3*2*1=6
4!=4*3*2*1=24
5!=5*4*3*2*1=120
factorial(n), n!,
.
alert(factorial(5));//120
: , n! n*(n1)!, 3!=3*2!=
3*2*1!=6
: 5
Fn=Fn1+Fn2. ,
.
1, 2(1+1), 3(1+2), 5(2+3) : 1,1,2,3,5,8,13,
21....
.
fib(n), n . :
functionfib(n){/**/}
alert(fib(3));//2
alert(fib(7));//13
alert(fib(77));//5527939700884757
JavaScript
, Named Function Expression ( NFE) , -,
.
sayHi:
a
r
f
=
f
u
n
c
t
i
o
n
s
a
y
H
i
(...){/**/};
v
, f, ?
(sayHi) .
.
JavaScript ,
IE8-.
:
varf=functionsayHi(name){
alert(sayHi);//()
};
alert(sayHi);//(:undefinedvariable'sayHi')
, NFE :
vartest=functionsayHi(name){
sayHi="";//
alert(sayHi);//function...()
};
test();
usestrict .
, NFE
.
NFE ,
.
,
.
, , - :
functionf(n){
returnn?n*f(n1):1;
};
alert(f(5));//120
g:
functionf(n){
returnn?n*f(n1):1;
};
varg=f;
f=null;
alert(g(5));//!
f.
, f=null.
, , Named Function Expression:
a
r
f
=
f
u
n
c
t
i
o
n
f
a
c
t
o
r
i
a
l
(n){
v
r
e
t
u
r
n
n
?
n
*
f
a
c
t
o
r
i
a
l(n1):1;
};
varg=f;//g
f=null;
alert(g(5));//120,!
IE8-
, IE 9 NFE ,
.
. IE
: f, factorial.
:
varf=functionfactorial(n){/*...*/};
//IE8false
//,..factorial
alert(f===factorial);
arguments.callee
JavaScript, , , ,
arguments.callee.
, ,
.
, ,
. NFE .
Function Expression, .
( IE8-).
,
.
, Function Declaration .
Function Expression.
NFE
: 5
?
functiong(){return1;}
alert(g);
? , ?
(functiong(){return1;});
alert(g);
: JavaScript
JavaScript, , ,
.
, ,
.
, .
:
alert('');alert('');
, . :
alert('')
alert('')
, JavaScript . :
vara=2
+3
alert(a);//5
, , ,
:
alert("")
[1,2].forEach(alert)
, ( [...] forEach) , ,
alert .
JavaScript . , ,
.
//... /*...*/:
: .
var. :
varx=5;
x="";
5 :
x=1;//
x="";//,
x=true;//true/false
x=null;//.()
x=undefined;//.()
Infinity() NaN.
NaN ,
.
null / - .
.
, , .
:
varage=null;//
undefined .
:
varx;
alert(x);//undefined
: x=undefined, .
, JavaScript
.
,
. $ _ .
: , , typeof.
,
, 'usestrict';
'usestrict';
...
.
, .
var. , , .
:
prompt([, _])
, null, .
confirm()
, . , , true/false.
alert()
.
, ..
.
:
varuserName=prompt("?","");
varisTeaWanted=confirm("?");
alert(":"+userName);
alert(":"+isTeaWanted);
+.
, :
alert(1+2);//3,
alert('1'+2);//'12',
alert(1+'2');//'12',
=== , .
.
==<<=>>= :
alert(0==false);//true
alert(true>0);//true
(. ).
: null undefined .
null==undefined . , .
( ===) null , undefined
NaN().
,
===. == , null
undefined.
, null:
alert(null>0);//false,..null0
alert(null>=0);//true,..null0
alert(null==0);//false,,nullundefined
. null ,
null>=0 true!
, unicode-.
, , :
alert(''>'');//true
: , .
JavaScript : ( &&), ( ||)
( !). .
, , , JavaScript
.
,
. , 1&&0&&2 &&, ..
( false).
.
-: , ,
, .
:
alert(0&&1);//0
alert(1&&2&&3);//3
alert(null||1||2);//1
: .
:
//1
while(){
...
}
//2
do{
...
}while();
//3
for(vari=0;i<10;i++){
...
}
, .
break/continue /
.
.
: _:, , :
u
t
e
r
:
o
for(;;){
...
for(;;){
...
b
r
e
a
k
o
u
t
e
r
;
}
}
,
. .
: while, for.
switch
switch ===.
:
varage=prompt('',18);
switch(age){
case18:
alert('');//prompt,
case"18"://!
alert('18!');
break;
default:
alert(',case');
}
: switch.
JavaScript:
//function(){}
functionsum(a,b){
varresult=a+b;
returnresult;
}
//:
alert(sum(1,2));//3
sum , , .
, var , ,
if, for .. .
a, b.
return undefined. return
undefined:
functionf(){}
alert(f());//undefined
: .
, ( ,
), Function Expression, ,
Function Declaration.
, Function Declaration, Function Expression ,
( ),
.
, ,
. , , ,
Function Expression.
: .
- , var=function...
, Function Expression.
, function.
.
.
, Function Expression
me:
varfactorial=functionme(n){
return(n==1)?n:n*me(n1);
}
alert(factorial(5));//120
alert(me);//,
IE8-,
.
: .
JavaScript,
, .
, , .
.
, , :
1. .
2. .
3. , .
Chrome
, , .
.
.
Chrome.
Firebug ( Firefox).
Sources
Chrome -, ,
.
Chrome.
: F12 >.
Sources.
:
1. . , JS/CSS.
pow.js, .
2. . .
3. . .
.
, . ,
, .
, .
. Esc.
, ,
.
pow.js Sources? 6 pow.js, 6.
! , , .
:
(breakpoint) . ,
JavaScript,
.
,
.., .
, , Breakpoints.
Breakpoints , , :
, .
.
Remove, .
, debugger:
functionpow(x,n){
...
debugger;//<
...
}
pow.js (conditional
breakpoint), .. , .
,
.
,
JavaScript . , F5(Windows, Linux)
Cmd+R(Mac).
, , 6 .
( ).
:
1. WatchExpressions .
, + .
,
.
2. CallStack , ,
.
, pow(pow.js, 6),
(index.html, 13).
3. ScopeVariables .
6 , result undefined.
Local : var .
this, , ,
, .
Global .
, , ( . trace )
.
-, 6 :
, F8.
.
, .
.
, , 6 pow, ..
( ) ,
.
, , CallStack
.
- , .
, , F10.
.
, .. .
, JS- -
, . ,
, .
, -
pow, pow ,
.
, F11.
. ,
.
.
, Shift+F11.
.
, ,
.
/ .
,
.
/ .
.
. Chrome ,
, .
,
, ,
.
, , ,
, , .
Continue to here
,
(Continue to here). ,
breakpoint .
, ,
JavaScript. .
, Console -,
,
ESC.
: console.log(...).
, :
//
for(vari=0;i<5;i++){
console.log("",i);
}
Chrome
Console API Chrome CommandLine API . Firebug (
Firefox).
, , IE10- ,
console.log .
.
JavaScript .
,
.
Console ( Ctrl+Shift+J/ Cmd+Shift+J).
- :
.
pow.js , ,
, .
?
.
.
:
1. Sources.
2. ,
3. .
JavaScript-
:
. - .
, ,
.
:
(breakpoint) debugger.
.
, ..
Google Chrome,
.
, , , , .
, Elements ( ), Timeline
, ..
:
1.
( .)
2. , . .
, HTML.
.
. .
( ):
, .
, . .
,
. , . JavaScript-
.
, if(cond)returnnull,
, , .
. , 80, 120,
, .
.
:
, ( ) .
, , ..
, Tab.
, :
show(""+
""+
""+
"");
, .
, .
, :
functionpow(x,n){
varresult=1;
//<
for(vari=0;i<n;i++){
result*=x;
}
//<
returnresult;
}
, .
9 .
, , , .
, , . JavaScript
, , , .
:
.
. ,
, .
( ) .
.
.
, continue,
if(..){...}:
:
for(vari=0;i<10;i++){
if(i){
...//<2
}
}
:
for(vari=0;i<10;i++){
i
f
(
i
)
c
o
n
t
i
n
u
e;
...//<1
}
if/else return. .
:
functionisEven(n){//
if(n%2==0){
returntrue;
}else{
returnfalse;
}
}
functionisEven(n){//
if(n%2==0){
returntrue;
}
returnfalse;
}
if return, else .
, ,
, .
isEven :
functionisEven(n){//
return!(n%2);
}
, !(n%2) ,
.
, .
, .
=
. .
, . ?
.
, , showPrimes(n) n.
:
functionshowPrimes(n){
nextPrime:for(vari=2;i<n;i++){
for(varj=2;j<i;j++){
if(i%j==0)continuenextPrime;
}
alert(i);//
}
}
isPrime(n) :
functionshowPrimes(n){
for(vari=2;i<n;i++){
i
f
(
!
i
s
P
r
i
m
e
(
i
)
)
c
o
n
t
i
n
u
e
;
alert(i);//
}
}
functionisPrime(n){
for(vari=2;i<n;i++){
if(n%i==0)returnfalse;
}
returntrue;
}
, ? ,
( isPrime).
, .
1. , :
/
/
functioncreateElement(){
...
}
functionsetHandler(elem){
...
}
functionwalkAround(){
...
}
/
/
varelem=createElement();
setHandler(elem);
walkAround();
2. , :
/
/
varelem=createElement();
setHandler(elem);
walkAround();
/
/
functioncreateElement(){
...
}
functionsetHandler(elem){
...
}
functionwalkAround(){
...
}
,
, , ?
, , .
, 2 .
, , ,
. ,
. , ,
, , .
.
, .
,
?
, ,
: .
, .
. : ,
, , , ,
, .
, , , ,
, .
, , , ,
. , :
?
?
, , .
, , .
. . ,
, .
, , UML
. .
, ,
.
JSDoc
/**
*xn,n
*
*@param{number}x.
*@param{number}n,.
*@return{number}xn.
*/
functionpow(x,n){
...
}
, ,
.
, , Aptana
JetBrains , ,
.
, , JSDoc 3 ,
HTML.
http://usejsdoc.org/ .
, ,
!
, , . , , , , ,
. , !
? .
:
. ?
, -, .
? ,
, - .
, , :
, - , , .
: , .
, , , . ,
. , ( ),
.
, , .
.
? ?
. , ,
.
,
,
.
, ,
, , ..
, ,
. , , , - .
, , :
Google JavaScript Style Guide
Idiomatic.JS
, , , .
, , ,
, .
, .
:
JSLint JSLint , -
, , .
JSHint
JSLint .
Closure Linter
, JSLint JSHint ,
, ,
.
, .
, .
- . JSHint .
.
.
( ) , , ,
, , .
: 4
?
functionpow(x,n)
{
varresult=1;
for(vari=0;i<n;i++){result*=x;}
returnresult;
}
x=prompt("x?",'')
n=prompt("n?",'')
if(n<=0)
{
alert(''+n+',,0');
}
else
{
alert(pow(x,n))
}
How To Write Unmaintainable Code
) , JavaScript.
, - .
,
JavaScript-.
, , JavaScript',
, !
, , , .
, , ,
, .
, .
. , ,
. . .
.
:
"
,,
,."
()
,
Helter
Shelter
, .
, . .
, , . ,
.
.
, , . ,
, .
,
, ,
? ,
, . ?
! , .
, , ,
!
jQuery
jQuery / DOM
jQuery/DOM, ,
, . .
jQuery wrap
varimg=$('<img/>');//(jQuery)
vardiv=$('<div/>');//
img.wrap(div);//imgdiv
div.append('<span/>');
wrap , :
<div>
<img/>
</div>
append?
, <span/> div, img !
,
.
, jQuery , . !
img.wrap(div) div img div,
. div , div, .
, div': img(
), span.
? - ? , ,
, , wrap .
jQuery-, clone .
, .
, .
!
, .
.
, .
'?', :
//jQuery
i=i?i<0?Math.max(0,len+i):i:0;
, , - i,
. , .
. .
: a, b c.
, .
, , .
i
, , ,
i, j, k. , !
- . , x y.
, - (
).
, , , .
, ..
!
- .
.
.
.
, obj, data,
value, item, elem ..
: data. , . ,
, ?
, data ? value, .
.
? .
, : obj, num, arr
? , !
, , ,
, ,
, !
, , .
? // ?
!
, ? : item1,item2,elem5,
data1
. ,
?
, data date.
.
, .
......
, .
,.
.
, - display..(,
displayElement), show..(showFrame).
,
, .
, .
display.., render.., paint...
,
! , print... printPage,
printText.
, : printMessage?.
. printMessage , , !
!
.
, , !
helloUser welcomeVisitor
, . - , ,
- .
user, visitor,
u. , .
-
!
, , .
.
.
, .
, ,
, .
.
(!)
, :
functionninjaFunction(elem){
//20,elem
elem=elem.cloneNode(true);
//20,elem
}
, elem , .
, , ,
!
: .
.
_ __ . ,
, .
. -, , -,
.
, ,
.
, , :
, , .
.
, ! superElement,
megaFrame niceItem
.
, , - : super.., mega.., nice..
.
- .
,
.
,,
.
?
.
a
r
u
s
e
r
=authenticateUser();
v
functionrender(){
a
r
u
s
e
r
=anotherValue();
v
...
......
...
...//<,..
...
}
render, , , user
, , authenticateUser()
! , .
!
, . .
, validateEmail(email), e-mail ,
e-mail.
, .
. -
, .
.
, , .
validateEmail(email), , .
.
.. --!
, , . , isReady,
checkPermission, findTags , ,
, .
.
- - ,
. .
, , ,
is.., check.. find...- ,
!
.
, is.. check.. true/false.
. checkPermission true/false,
! , .
, if(checkPermission(..)),
. : !. .
.
, , ;)
.
, .
,
.
chai mocha
.
, , .
?
, ,
.
, , , .
, , , .
- ,
.
.
.
, f. , . f(a)
, f(b) . f(b), .
f(a) , .
,
.
BDD
, BDD Behavior Driven Development.
BDD .
BDD . .
BDD :
.
, . .
pow:
, pow(x,n), x n,
n0.
,
BDD.
(, , ) :
describe("pow",function(){
it("n",function(){
assert.equal(pow(2,3),8);
});
});
, :
describe(,function(){...})
, , it.
pow.
it(,function(){...})
it , ,
, .
assert.equal(value1,value2)
it, , .
assert.*, , pow, .
assert.equal,
, . ,
pow(2,3) 8.
, .
, :
1. , .
2. .
3. ,
Mocha . it
, . .
4. , , , ,
.
5. 3, , , .
, ,
.
, ,
. , ,
, .
JavaScript-.
:
Mocha
, describe it.
Chai .
, ,
assert.equal.
Sinon
, .
JS , Node.JS.
, .
HTML- :
<!DOCTYPEhtml>
<html>
<head>
<metacharset="utf8">
<!Mocha,>
<linkrel="stylesheet"href="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.css">
<!Mocha>
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.js"></script>
<!Mocha:BDD>
<script>
mocha.setup('bdd');
</script>
<!chai>
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/chai/2.0.0/chai.js"></script>
<!chai,assert>
<script>
varassert=chai.assert;
</script>
</head>
<body>
<script>
functionpow(x,n){
/*,*/
}
</script>
<!>
<scriptsrc="test.js"></script>
<!id="mocha">
<divid="mocha"></div>
<!!>
<script>
mocha.run();
</script>
</body>
</html>
:
1. <head> , .
2. <script> , pow.
3. , test.js describe("pow",...),
. describe it Mocha, ,
.
4. <divid="mocha"> Mocha .
mocha.run().
:
pow
n-
, , .
, ,
, .
, describe(""...).
, ,
.
, , , .
pow, :
functionpow(){
return8;//:)!
}
, :
pow
n-
, , , . :)
, ( !)
, , , , .
BDD, .
, , ()
.
, pow(3,4)=81.
:
1. assert it:
describe("pow",function(){
it("n",function(){
assert.equal(pow(2,3),8);
assert.equal(pow(3,4),81);
});
});
2. :
describe("pow",function(){
it("238",function(){
assert.equal(pow(2,3),8);
});
it("3481",function(){
assert.equal(pow(3,4),81);
});
});
, assert ,
it. , assert,
.
, ,
.
, , .
.
,
.
.
:
pow
2 3 8
3 4 81
, . , 8.
, :
functionpow(x,n){
varresult=1;
for(vari=0;i<n;i++){
result*=x;
}
returnresult;
}
, ,
. , it,
for:
describe("pow",function(){
functionmakeTest(x){
varexpected=x*x*x;
it(""+x+"3:"+expected,function(){
assert.equal(pow(x,3),expected);
});
}
for(varx=1;x<=5;x++){
makeTest(x);
}
});
pow
1 3 : 1
2 3 : 8
3 3 : 27
4 3 : 64
5 3 : 125
describe
makeTest for, , , ,
. ,
n- .
, describe:
describe("pow",function(){
describe("xn",function(){
functionmakeTest(x){
varexpected=x*x*x;
it(""+x+"3:"+expected,function(){
assert.equal(pow(x,3),expected);
});
}
for(varx=1;x<=5;x++){
makeTest(x);
}
});
//...itdescribe...
});
describe , it ,
, , :
pow
x n
1 3 : 1
2 3 : 8
3 3 : 27
4 3 : 64
5 3 : 125
it describe
.
before/after beforeEach/afterEach
describe before/after,
/ , beforeEach/afterEach, /
it.
:
describe("",function(){
before(function(){alert("");});
after(function(){alert("");});
beforeEach(function(){alert("");});
afterEach(function(){alert("");});
it('1',function(){alert('1');});
it('2',function(){alert('2');});
});
, beforeEach/afterEach(before/each) ,
, - (
).
pow , .
.
, pow(x,n)
n.
JavaScript NaN,
n.
:
describe("pow",function(){
//...
it("NaN",function(){
assert(isNaN(pow(2,1)));
});
it("NaN",function(){
assert(isNaN(pow(2,1.5)));
});
});
pow
NaN
, , .
: , .
assert
, assert.equal, ,
assert(). ,
true.
, NaN : NaN
, , assert.equal(NaN,x) .
, assert(value1==value2) assert.equal(value1,
value2). assert .
, .
assert "UnspecifiedAssertionError",
- , assert.equal(value1,value2) :
expected8toequal81.
,
.
assert-, Chai:
assert(value) value true .
assert.equal(value1,value2) value1==value2.
assert.strictEqual(value1,value2) value1===value2.
assert.notEqual, assert.notStrictEqual , .
assert.isTrue(value) , value===true
assert.isFalse(value) , value===false
assert.isNaN, , , ,
assert(...). ,
, assert.
assert
, , assert .
assert':
describe("pow",function(){
//...
it("NaN",function(){
assert(isNaN(pow(2,1)),"pow(2,1)NaN");
});
it("NaN",function(){
assert(isNaN(pow(2,1.5)),"pow(2,1.5)NaN");
});
});
, :
pow
NaN
assert.equal, :
assert.equal(value1,value2,""), ,
.
, , ,
.
, - :
describe("pow",function(){
describe("xn",function(){
functionmakeTest(x){
varexpected=x*x*x;
it(""+x+"3:"+expected,function(){
assert.equal(pow(x,3),expected);
});
}
for(varx=1;x<=5;x++){
makeTest(x);
}
});
it("NaN",function(){
assert(isNaN(pow(2,1)),"pow(2,1)NaN");
});
it("NaN",function(){
assert(isNaN(pow(2,1.5)),"pow(2,1.5)NaN");
});
describe(",,01",function(){
functionmakeTest(x){
it(""+x+"0:1",function(){
assert.equal(pow(x,0),1);
});
}
for(varx=5;x<=5;x+=2){
makeTest(x);
}
});
it("NaN",function(){
assert(isNaN(pow(0,0)),"00NaN");
});
});
:
1. , .
2. , .
3. , it.
, , ,
, .
.
, ,
. - ,
,
.
, , ,
, . ,
.
, , !
-
. ,
, - .
, , , .
, , . .
, ,
, , .
.
, . .
, . -,
.
?
.
.
, , .
pow
: 5
pow, .
.
HTML . , HTML- ,
chai mocha.
Chai, Mocha Sinon :
<scriptsrc="https://js.cx/test/libs.js"></script>
, , mocha.run
. id="mocha", <body>.
,
.
.
: 5
, , , ,
1, NaN( ,
00 ).
, , .
.
?
: 5
pow?
it("xn",function(){
varx=5;
varresult=x;
assert.equal(pow(x,1),result);
varresult*=x;
assert.equal(pow(x,2),result);
varresult*=x;
assert.equal(pow(x,3),result);
});
P.S. , .
JavaScript: , .
JavaScript, null undefined,
, .
, .
.
str.length
length, :
alert(",!".length);//12
, :
varstr=",!";
alert(str.length);//12
str.toUpperCase()
toUpperCase(), :
varhello=",!";
alert(hello.toUpperCase());//",!"
!
, .
, , toUpperCase :
varhello="";
alert(hello.toUpperCase);//function...
(, ),
. .
- : "functiontoUpperCase(){...}".
, :
varhello="";
alert(hello.toUpperCase());//
num.toFixed(n)
, num.toFixed(n). num n ,
(
):
varn=12.345;
alert(n.toFixed(2));//"12.35"
alert(n.toFixed(0));//"12"
alert(n.toFixed(5));//"12.34500"
toFixed .
:
alert(12.34.toFixed(1));//12.3
, :
alert(12.toFixed(1));//!
, JavaScript .
JavaScript. :
alert(12..toFixed(1));//12.0
.
JavaScript, null undefined
.
JavaScript.
JavaScript , (
0x), ( 0) :
alert(0xFF);//255
alert(010);//8
( ),
<>e<>.
, 1e3 1 3, 1000.
//:35
alert(3e5);//300000
, ,
:
//35,.
alert(3e5);//0.00003<5,
, Infinity
, JavaScript (
LiveScript ).
?
, ,
.
JavaScript . ,
. -
. ,
, 0 ,
, JavaScript: "Infinity".
alert(1/0);//Infinity
alert(12345/0);//Infinity
Infinity ,
.
Infinity .
.
alert(Infinity>1234567890);//true
alert(Infinity+5==Infinity);//true
: varx=Infinity.
Infinity:
alert(1/0);//Infinity
, ,
64- , :
alert(1e500);//Infinity
NaN
,
NaN(Not-A-Number).
, 0/0 , NaN:
alert(0/0);//NaN
NaN
:
NaN , , , .
:
if(NaN==NaN)alert("==");//
if(NaN===NaN)alert("===");//
NaN isNaN(n),
true, NaN, false .
varn=0/0;
alert(isNaN(n));//true
alert(isNaN("12"));//false,12
NaN
NaN:
, NaN:
varn=0/0;
if(n!==n)alert('n=NaN!');
, isNaN(n).
alert(NaN+1);//NaN
isNaN , .
JS
JavaScript
.
, NaN.
isFinite(n)
, JavaScript : NaN, Infinity
Infinity.
, , , , +:
varvalue=prompt("Infinity",'Infinity');
varnumber=+value;
alert(number);//Infinity,"Infinity"""
, Infinity NaN .
, ,
isFinite.
isFinite(n) true,
NaN/Infinity/Infinity:
alert(isFinite(1));//true
alert(isFinite(Infinity));//false
alert(isFinite(NaN));//false
.
, , '+':
vars="12.34";
alert(+s);//12.34
, , NaN:
alert(+"12test");//NaN
,
:
alert(+"12");//12
alert(+"\n34\n");//34,\n
alert(+"");//0,
alert(+"12");//NaN,
:
alert('12.34'/"2");//6.17
: parseInt parseFloat
HTML/CSS . , CSS: 10pt
12px.
'+' NaN:
alert(+"12px")//NaN
parseInt:
alert(parseInt('12px'));//12
parseInt parseFloat ,
.
, . parseInt
, parseFloat .
alert(parseInt('12px'))//12,'p'
alert(parseFloat('12.3.4'))//12.3,
, , parseInt/parseFloat NaN.
:
alert(parseInt('a123'));//NaN
isNaN(str).
+, true, NaN, ..
:
varx=prompt("","11.5");
if(isNaN(x)){
alert("NaN.");
}else{
alert("");
}
, :
1. 0, .
2. , , isNaN
false,true,null, ,
.
alert(isNaN(null));//falseNaN,..""
alert(isNaN("\n\n"));//falseNaN,..""
, isNaN .
,
, , Infinity
isNumeric:
functionisNumeric(n){
return!isNaN(parseFloat(n))&&isFinite(n);
}
, . .
isFinite(n) true, Infinity/
Infinity/NaN.
, -,
true/false/null '', .. .
. parseFloat(true/false/null/'') NaN
.
parseFloat: , .. true/false/null
"true"/"false"/"null", ,
NaN.
, - .
toString( )
, 10-, 16- .
: 16- .
toString(), :
varn=255;
alert(n.toString(16));//ff
, , #AABBCC.
2 36.
2 :
varn=4;
alert(n.toString(2));//100
varn=1234567890;
alert(n.toString(36));//kf12oi
,
URL.
. JavaScript 3
.
Math.floor
Math.ceil
Math.round
alert(Math.floor(3.1));//3
alert(Math.ceil(3.1));//4
alert(Math.round(3.1));//3
32- , .
, , ,
:
alert(~~12.3);//12
, XOR ( , "^")
:
alert(12.3^0);//12
alert(1.2+1.3^0);//2,^,+
,
Math.floor(...):
varx=a*b/c^0;//"a*b/c"
10
. , 3.456 2 :
varn=3.456;
alert(Math.round(n*100)/100);//3.456>345.6>346>3.46
num.toFixed(precision)
num.toFixed(precision), num
precision :
varn=12.34;
alert(n.toFixed(1));//"12.3"
, Math.round:
varn=12.36;
alert(n.toFixed(1));//"12.4"
, , :
varn=12.34;
alert(n.toFixed(5));//"12.34000",5
, , '+' n.toFixed(..):
varn=12.34;
alert(+n.toFixed(5));//12.34
toFixed Math.round!
,
: toFixed Math.round :
varprice=6.35;
alert(price.toFixed(1));//6.3
alert(Math.round(price*10)/10);//6.4
, ! Math.round
, 5 . toFixed
, . ? !
:
alert(0.1+0.2==0.3);
? .
, . false. , ? ,
? , .
, : 0.1+0.2 0.3. ?
alert(0.1+0.2);//0.30000000000000004
, , 0.1+0.2
, 0.3.
alert(0.1+0.2>0.3);//true
0.1() ,
( ).
0.2(=2/10).
,
. :
alert(0.1.toFixed(20));//0.10000000000000000555
0.1 0.2, , ,
.
, , . .
.
, 0.1 0.2:
1. , , :
alert((0.1*10+0.2*10)/10);//0.3
, .. 0.1*10=1 0.2*10=2
.
2. , . 10-
, :
varresult=0.1+0.2;
alert(+result.toFixed(10));//0.3
! , !
alert(9999999999999999);//10000000000000000
.
64, , 52, 11
. 52 ,
.
, ,
. : , .
, ,
IEEE 754, Java, C, PHP, Ruby, Perl.
JavaScript
.
:
Math.acos(x)
x( )
Math.asin(x)
x( )
Math.atan(x)
x( )
Math.atan2(y,x)
(y,x). : Atan2
Math.sin(x)
x( )
Math.cos(x)
x( )
Math.tan(x)
x( )
:
Math.sqrt(x)
x.
Math.log(x)
( e) x.
Math.pow(x,exp)
, xexp, Math.pow(2,3)=8.
, : Math.pow(4,1/2)=0.5.
Math.abs(x)
Math.exp(x)
ex, e .
Math.max(a,b,c...)
Math.min(a,b,c...)
Math.random()
- [0,1) 0() 1(
). .
ECMA 402
toLocaleString():
varnumber=123456789;
alert(number.toLocaleString());//123456789
, IE10- (
Intl.JS ). .
Intl: JavaScript,
.
, ,
.
JavaScript Infinity.
NaN.
,
.
parseInt/parseFloat , .
: Math.floor, Math.round, Math.ceil .
+n.toFixed(p)
10p.
.
.
0 1 Math.random(),
.
.
Number Math.
: 5
, .
P.S. .
6.35.toFixed(1) == 6.3?
: 4
, 5 , :
alert(1.5.toFixed(0));//2
alert(1.35.toFixed(1));//1.4
6.35 6.3?
alert(6.35.toFixed(1));//6.3
: 5
. (, ..).
. ,
.
.
, 0.10$ 0.20$
0.30000000000000004$:
alert(0.1+0.2+'$');
, ?
: 4
. ?
vari=0;
while(i!=10){
i+=0.2;
}
?
: 4
getDecimal(num), :
alert(getDecimal(12.345));//0.345
alert(getDecimal(1.2));//0.2
alert(getDecimal(1.2));//0.2
: 4
Fn=Fn1+Fn2. ,
.
1, 2(1+1), 3(1+2), 5(2+3) : 1,1,2,3,5,8,13,
21....
( ):
functionfib(n){
vara=1,
b=0,
x;
for(i=0;i<n;i++){
x=a+b;
a=b
b=x;
}
returnb;
}
Fn n/5, =
(1+5)/2 .
fibBinet(n), Fn, .
F77( fibBinet(77)=5527939700884757).
, fib(n) ?
, ?
(0, max)
: 2
0 max, max.
(min, max)
: 2
min max, max.
min max
: 2
randomInteger(min,max) min
max, min,max .
min..max .
JavaScript . ,
.
, ,
(Unicode) .
:
vartext="";
varanotherText='';
varstr="012345";
JavaScript .
.
.
\n, :
alert('\n');//""
, :
\b
Backspace
\f
Form feed
\n
New line
\r
Carriage return
\t
\uNNNN
Tab
NNNN. , \u00A9
,
, \', :
a
r
s
t
r
=
'
I
\
'
m
aJavaScriptprogrammer';
v
:
varstr="I'maJavaScript\"programmer\"";
alert(str);//I'maJavaScript"programmer"
JavaScript.
'\'. , .
'\' , , .
\\:
varstr='\\';
alert(str);//\
. , :
alert("\a");//a
//alert("a");
, ,
.
length
:
varstr="My\n";//3.
alert(str.length);//3
, charAt(). 0:
varstr="jQuery";
alert(str.charAt(0));//"j"
JavaScript , charAt ,
.
:
varstr="!";
alert(str[0]);//""
charAt , charAt
, undefined:
alert("".charAt(0));//
alert(""[0]);//undefined
charAt ,
.
, str.length , str.charAt(pos) , ..
.
, .
JavaScript . , .
.
, :
varstr="";
str=str[3]+str[4]+str[5];
alert(str);//
toLowerCase() toUpperCase() /:
alert("".toUpperCase());//
:
alert(""[0].toLowerCase());//''
indexOf([, _])
, 1, .
:
varstr="Widgetwithid";
alert(str.indexOf("Widget"));//0,.."Widget"str
alert(str.indexOf("id"));//1,.."id",1
alert(str.indexOf("widget"));//1,,
, . ,
"id" 1.
2:
varstr="Widgetwithid";
alert(str.indexOf("id",2))//12,2
lastIndexOf
, .
:
indexOf '~'.
, ~n (n+1), :
alert(~2);//(2+1)=3
alert(~1);//(1+1)=2
alert(~0);//(0+1)=1
alert(~1);//(1+1)=0
, ~n , n==1.
, if(~str.indexOf(...)), indexOf 1, ..
.
:
varstr="Widget";
if(~str.indexOf("get")){
alert('!');
}
, ,
.
, , . : '~' ,
"if~str.indexOf" "".
, indexOf .
.
:
varstr="";//
vartarget="";//
varpos=0;
while(true){
varfoundPos=str.indexOf(target,pos);
if(foundPos==1)break;
alert(foundPos);//
pos=foundPos+1;//
}
0, foundPos,
pos=foundPos+1, , - .
, :
varstr="";//
vartarget="";//
varpos=1;
while((pos=str.indexOf(target,pos+1))!=1){
alert(pos);
}
a
r
s
t
r
=
"
s
tringify";
v
alert(str.substring(0,1));//"s",011.
end, :
a
r
s
t
r
=
"
s
t
r
i
n
g
i
f
y
";
v
alert(str.substring(2));//ringify,2
substr(start[,length])
, substring, ,
.
a
r
s
t
r
=
"
s
t
r
i
n
g
ify";
v
str=str.substr(2,4);//ring,24
alert(str)
.
slice(start[,end])
start, , end.
substring.
substring slice ,
:
substring(start,end)
.
:
alert("testme".substring(2));//"testme",20
, start>end, , ..
start end:
alert("testme".substring(4,1));//"test"
//10>substring(4,0)
//4>0,>substring(0,4)="test"
slice
:
alert("testme".slice(2));//"me",2
alert("testme".slice(1,1));//"estm",1.
, substring.
substr , IE8-.
,
slice: .
, ''<''<''<...<''.
..
1. '' ''?
alert(''>'');//true
alert(''>'');//true
, JavaScript.
, , windows-1251 utf-8.
JavaScript- .
.
:
String.fromCharCode(code)
code:
alert(String.fromCharCode(1072));//''
:
str.charCodeAt(pos)
pos. .
alert("".charCodeAt(0));//1072,''
. ''>'' ''>''
?
, , .
. .
, .
1034 1113:
varstr='';
for(vari=1034;i<=1113;i++){
str+=String.fromCharCode(i);
}
alert(str);
:
1. , .
, ''(1072)>''(1071).
, 'a'>'Z'.
2. , , .
, , , ''(1105)>''(
1103).
HTML
, , HTML,
(numeric character reference).
&#, , ';'. ,
'' : а.
16- , &#x.
, , : (✂),
: (½) (¾) . .
, , .
s1 s2 :
1. : s1[0] s2[0]. , ,
, true false. ,
2. s1[1] s2[1]
3. s1[2] s2[2] , ,
. - ,
, , .
.
, ,
.
"">""//true,..,''>''
"">""//true,..,1
, , prompt.
:
alert("2">"14");//true,,"2">"1"
, :
alert(2>"14");//false
, IE10- ( Intl.JS )
ECMA 402 , ,
.
:
varstr="";
alert(str.localeCompare(""));//1
JavaScript .
, \n .
length charAt, toLowerCase/toUpperCase,
substring/substr/slice( slice). , trim
.
. ,
, number.
, .
, .
ECMA 402. ,
. , IE10-,
https://github.com/andyearnshaw/Intl.js/ .
str1.localeCompare(str2).
: http://javascript.ru/String.
: 5
ucFirst(str), str ,
:
ucFirst("")=="";
ucFirst("")=="";//
: 5
checkSpam(str), true, str 'viagra' or
'XXX', false.
:
checkSpam('buyViAgRAnow')==true
checkSpam('freexxxxx')==true
checkSpam("innocentrabbit")==false
: 5
truncate(str,maxlength), str,
maxlength str "...", maxlength.
( ) .
:
truncate(",:",20)=",..."
truncate("!",20)="!"
. ,
.
.
: 4
: "$120". , , .
extractCurrencyValue(str), , 120.
.
JavaScript .
: , .
.
- .
.
-.
. .
, .
,
. , .
,
.
( ) :
1.o=newObject();
2.o={};//
(2), .. .
, .
( ).
, person :
varperson={};//
, .
, ., :
//""
//"name"''
person.name='';
person.age=25;//:'age'25
. , : ,
.
:
alert(person.name+':'+person.age);//":25"
delete:
deleteperson.age;
name:
:
4. .
in.
: "prop"inobj, , :
if("name"inperson){
alert("name!");
}
, undefined.
, JavaScript , .
.
, undefined:
varperson={};
alert(person.lalala);//undefined,lalala
undefined:
varperson={
name:""
};
alert(person.lalala===undefined);//true,
alert(person.name===undefined);//false,.
in ===undefined
: in,
undefined.
, .
, , undefined:
varobj={};
obj.test=undefined;//undefined
//testblabla
alert(obj.test===undefined);//true
alert(obj.blabla===undefined);//true
, ,
.
in :
varobj={};
obj.test=undefined;
alert("test"inobj);//true
alert("blabla"inobj);//false
, undefined,
. , ,
null.
,
['']:
varperson={};
person['name']='';//person.name=''
person['name'] person.name,
:
varperson={};
person['']='';//person.name=''
, , :
person.='';//???
, .
JavaScript .
, :
varperson={
age:25
};
varkey='age';
alert(person[key]);//person['age']
, (varkey="age"),
person[key].
,
. , ,
, .
, : {1:
1,2:2,...}.
(. literal).
:
varmenuSetup={
width:300,
height:200,
title:"Menu"
};
//,:
varmenuSetup={};
menuSetup.width=300;
menuSetup.height=200;
menuSetup.title='Menu';
, ,
.
:
varmenuSetup={
width:300,
'height':200,
"":true
};
:
varuser={
name:"",
age:25,
size:{
top:90,
middle:60,
bottom:90
}
}
alert(user.name)//""
alert(user.size.top)//90
size {top:90,middle:60,bottom:90}.
,
, .
, :
varuser={
name:"Vasya",
age:25
};
name , age
. , .
, name age .
, .
( )
.
.
, name age:
{name:"",age:25}
{name:"",age:22}
{name:"",age:19}
...
, .
: <stringname,numberage>.
:
<:stringname,numberage>
25
22
19
,
. .
, ? ,
isAdmin:
user.isAdmin=true;
, , .
.
, , , --
.
, .
.
, Chrome , , Know Your Engines .
, .
:
:
obj.prop=5
, :
varkey="prop";
obj[key]=5
: deleteobj.name.
in: if("prop"inobj), ,
if(obj.prop!==undefined).
: 3
- . , .
1. user.
2. name .
3. surname .
4. name .
5. name .
:
for..in.
for(;;).
for..in
:
for(keyinobj){
/*...obj[key]...*/
}
for..in obj,
key .
for(varkeyinobj)
key :
o
r
(
v
a
r
k
e
y
inmenu){
f
//...
}
. , key,
for(varpropNameinmenu).
:
varmenu={
width:300,
height:200,
title:"Menu"
};
for(varkeyinmenu){
//
//..
alert(":"+key+":"+menu[key]);
}
, menu[key]. ,
, , .
, ?
.
- , :
varmenu={
width:300,
height:200,
title:"Menu"
};
varcounter=0;
for(varkeyinmenu){
counter++;
}
alert(":"+counter);
, , :
Object.keys(menu).length.
?
, , :
varcodes={
//"":""
"7":"",
"38":"",
//..,
"1":""
};
, , 7,
.
, .
select, , .
, for(keyincodes) key
, ?
. , , .
, ,
. :
.
, ,
.
, :
varuser={
name:"",
surname:""
};
user.age=25;
//
for(varpropinuser){
alert(prop);//name,surname,age
}
, ?
varcodes={
//"":""
"7":"",
"38":"",
"1":""
};
for(varcodeincodes)alert(code);//1,7,38
, !
, . JavaScript ,
.
.
, , , ?
. , ,
, , '+':
varcodes={
"+7":"",
"+38":"",
"+1":""
};
for(varcodeincodes){
varvalue=codes[code];
code=+code;//..,:"+7">7
alert(code+":"+value);//7,38,1
}
: for(keyinobj).
,
( ).
, ,
: , .
, +, , , ,
.
,
: 5
isEmpty(obj), true, false
.
:
functionisEmpty(obj){
/**/
}
varschedule={};
alert(isEmpty(schedule));//true
schedule["8:30"]="";
alert(isEmpty(schedule));//false
: 5
salaries . , .
, 0.
:
"usestrict";
varsalaries={
"":100,
"":300,
"":250
};
//...650
P.S. usestrict, .
: 5
salaries . , ,
.
, .
:
"usestrict";
varsalaries={
"":100,
"":300,
"":250
};
//...""
2
: 3
multiplyNumeric,
2. :
//
varmenu={
width:200,
height:300,
title:"Mymenu"
};
multiplyNumeric(menu);
//
menu={
width:400,
height:600,
title:"Mymenu"
};
P.S. :
functionisNumeric(n){
return!isNaN(parseFloat(n))&&isFinite(n)
}
:
,
.
: , , , null/undefined
, , .
varmessage="";
varphrase=message;
,
"".
.
, , ,
, .
, :
varuser={
name:""
};
: . () .
, -
.
:
varuser={name:""};//
varadmin=user;//
, :
:
varuser={name:''};
varadmin=user;
d
m
i
n
.
n
a
m
e
='';//admin
a
l
e
r
t
(
u
s
e
r
.
n
a
m
e
);//'',user
a
: , ,
, , .
, , - .
, , ,
, .
, . ,
.
:
varuser={
name:"",
age:30
};
varclone={};//
//user
for(varkeyinuser){
clone[key]=user[key];
}
//clone
clone.name="";//clone
alert(user.name);//""
user clone. ,
, .
, , ,
. .
( F12) :
vartime={
year:2345,
month:11,
day:10,
hour:11,
minute:12,
second:13,
microsecond:123456
}
console.log(time);//(*)
time.microsecond++;//(**)
console.log(time);
time.microsecond++;
console.log(time);
time.microsecond++;
, (*), (**)
, . ,
- , .
!
( Chrome):
, microsecond 123459 ?
, , ! , .
(
) .
, ,
. , ,
.
. , ,
, , .
- , ,
.
(, ),
, .
c
,
.
,
, ..
.
:
vararr=[];
fruits :
varfruits=["","",""];
, .
:
varfruits=["","",""];
alert(fruits[0]);//
alert(fruits[1]);//
alert(fruits[2]);//
:
fruits[2]='';//["","",""]
:
fruits[3]='';//["","","",""]
, , length:
varfruits=["","",""];
alert(fruits.length);//3
alert .
:
varfruits=["","",""];
alert(fruits);//,,
.
, , , , :
//
vararr=[1,'',{name:''},true];
//
alert(arr[2].name);//
pop/push, shift/unshift
.
, ,
.
. , ,
.
:
, , ,
.
, ,
.
pop
:
varfruits=["","",""];
alert(fruits.pop());//""
alert(fruits);//,
push
:
varfruits=["",""];
fruits.push("");
alert(fruits);//,,
fruits.push(...) fruits[fruits.length]=....
shift
:
varfruits=["","",""];
alert(fruits.shift());//
alert(fruits);//,
unshift
:
varfruits=["",""];
fruits.unshift('');
alert(fruits);//,,
push unshift :
varfruits=[""];
fruits.push("","");
fruits.unshift("","");
//:["","","","",""]
alert(fruits);
, ,
length.
, :
functioneat(arr){
arr.pop();
}
vararr=["","","","",""]
alert(arr.length);//5
eat(arr);
eat(arr);
alert(arr.length);//3,,
.
:
varfruits=[];//
fruits[99999]=5;//
fruits.age=25;//
.. JavaScript, ,
. length.
, ,
.
,
, :
vara=[];
a[0]=0;
a[5]=5;
alert(a);//0,,,,,5
, 0 arr.length
. .
push/pop , shift/unshift .
, , ,
:
fruits.shift();//1
, , 0
. .
shift :
1. .
2. , 1 0, 2 1 .
3. length.
, ,
.
unshift: ,
, , .
push/pop? . , ,
pop length.
:
fruits.pop();//1
pop ,
.
push.
:
vararr=["","",""];
for(vari=0;i<arr.length;i++){
alert(arr[i]);
}
for..in
, for..in:
vararr=["","",""];
for(varkeyinarr){
alert(arr[key]);//,,
}
:
1. for..in , .
, , ,
, .
for..in ,
.
, . for
, .
2. for(vari=0;i<arr.length;i++) 10-100
. , ,
.
: for(vari=0;i<arr.length...) .
length
length.
length , +1.
.
:
vararr=[];
arr[1000]=true;
l
e
r
t
(
a
r
r
.
l
e
n
g
t
h
)
;
/
/
1
0
0
1
, ,
, .
.
length
length ,
.
length .
, .. length
:
vararr=[1,2,3,4,5];
arr.length=2;//2
alert(arr);//[1,2]
arr.length=5;//length,
alert(arr[3]);//undefined:
arr.length=0.
new Array
new Array()
:
a
r
a
r
r
=
n
e
w
A
r
r
a
y
("","","..");
v
, .. [].
, . newArray(,...)
, - newArray(),
, .
:
vararr=newArray(2,3);
alert(arr[0]);//2,[2,3],
arr=newArray(2);//[2]?
alert(arr[0]);//undefined!,2
, ? ?
, {length:2}.
, undefined.
, .
JavaScript .
, :
varmatrix=[
[1,2,3],
[4,5,6],
[7,8,9]
];
alert(matrix[1][1]);//
, , , ,
length. , , -.
-, ,
.
,
, .
.
, .
:
, arr.test=5. ,
, .
.
, arr[0], arr[1000],
, . ,
-.
, .
.
:
//
vararr=[1,2...];
//newArray
vararr=newArray(1,2...);
newArray() , . ,
.
length . , 1.
, . length ,
undefined.
.
:
arr.push(1,2...) .
varelem=arr.pop() .
:
arr.unshift(1,2...) .
varelem=arr.shift() .
, .
.
: 5
?
goods. , goods.length.
goods.
: 5
?
goods. .
: 5
5 -:
1. styles , .
2. --
3. .
.
4. alert.
5. .
:
,
,,
,,
,
,,,
: 3
alert :
vararr=["","","",""];
: 4
, :
prompt .
, , .
0 , .
?
: 3
?
vararr=[1,2,3];
vararr2=arr;
arr2[0]=5;
alert(arr[0]);
alert(arr2[0]);
: 3
find(arr,value), arr value
, , 1, .
:
arr=["test",2,1.5,false];
find(arr,"test");//0
find(arr,2);//1
find(arr,1.5);//2
find(arr,0);//1
: 3
filterRange(arr,a,b), arr
, arr a b. ,
aarr[i]b. arr.
:
vararr=[5,4,3,8,0];
varfiltered=filterRange(arr,3,5);
//filtered=[5,4,3]
//arr
: 3
, 1, , ,
1.
n :
1. 2 n: 2,3,4,...,n.
2. p=2, .
3. p, .. 2*p,3*p,4*p .. p=2
4,6,8....
4. p p.
5. 3-4 p2<n.
6. .
JavaScript, .
100 .
: 2
, : arr=[1,2,3,4,9,6].
arr, .
.
:
e
t
M
a
x
S
u
b
S
u
m
(
[
1
,
2
,
3
,9])=5()
g
e
t
M
a
x
S
u
b
S
u
m
(
[
2
,
1
,
2
,
3
,9])=6
g
g
e
t
M
a
x
S
u
b
S
u
m
(
[
1
,
2
,
3
,
9
,
1
1])=11
e
t
M
a
x
S
u
b
S
u
m
(
[
2
,
1
,
1
,
2
])=3
g
e
t
M
a
x
S
u
b
S
u
m
(
[
1
0
0
,9,2,3,5])=100
g
g
e
t
M
a
x
S
u
b
S
u
m
(
[
1
,
2
,
3])=6()
, :
getMaxSubSum([1,2,3])=0
, O(n2), O(n) .
.
:
JavaScript.
split
. ,
: ,,,.... -
, .
, split(s), ,
s. .
varnames=',,,';
vararr=names.split(',');
for(vari=0;i<arr.length;i++){
alert(''+arr[i]);
}
split
split
. , :
l
e
r
t
(
"
a
,
b
,
c
,
d
"
.
s
p
l
i
t
(
'
,
'
,
2
));//a,b
a
split :
varstr="";
alert(str.split(''));//,,,
join
arr.join(str) split.
, str .
:
vararr=['','','',''];
varstr=arr.join(';');
alert(str);//;;;
alert(newArray(4).join(""));//
, newArray(4) 4, join
, "".
, , .
.
,
delete:
vararr=["","",""];
deletearr[1];//1
//arr=["",undefined,""];
alert(arr[1]);//undefined
, , , . .
, delete -. , .
,
.
: shift, pop,
splice, .
splice
splice . :
, , .
:
arr.splice(index[,deleteCount,elem1,...,elemN])
deleteCount, index, elem1,...,elemN
. .
, .
:
vararr=["","","JavaScript"];
arr.splice(1,1);//1,1
alert(arr);//["","JavaScript"]
3 :
a
r
a
r
r
=
[
"
"
,
"
"
,
"
"
,
"JavaScript"];
v
//3
arr.splice(0,3,"","")
a
l
e
r
t
(
a
r
r
)
/
/
[
"
"
,
"
","JavaScript"]
, splice :
a
r
a
r
r
=
[
"
"
,
"
"
,
"","JavaScript"];
v
//2
varremoved=arr.splice(0,2);
alert(removed);//"",""<arrayofremovedelements
splice ,
deleteCount 0:
vararr=["","","JavaScript"];
//2
//0
//"",""
arr.splice(2,0,"","");
alert(arr);//"","","","","JavaScript"
,
:
vararr=[1,2,5]
//1()
//0,
//34
arr.splice(1,0,3,4);
alert(arr);//:1,2,3,4,5
slice
slice(begin,end) begin end, end.
.
:
vararr=["","","","JavaScript"];
vararr2=arr.slice(1,3);//1,2(3)
alert(arr2);//,
, slice:
end :
vararr=["","","","JavaScript"];
alert(arr.slice(1));//,1
, :
vararr2=arr.slice(2);//2
:
varfullCopy=arr.slice();
slice . .
, sort(fn)
sort() . :
vararr=[1,2,15];
arr.sort();
l
e
r
t
(
a
r
r
)
;
/
/
1
,
1
5
,
2
?
1,15,2, . ?
, sort, .
, "2">"15".
arr.sort(fn) fn
, .
, ,
, . ,
. fn.
, .
, , :
functioncompareNumeric(a,b){
if(a>b)return1;
if(a<b)return1;
}
vararr=[1,2,15];
arr.sort(compareNumeric);
a
l
e
r
t
(
a
r
r
)
;
/
/
1
,
2
,
1
5
, sort() compareNumeric,
. :
a
r
r
.
s
o
r
t
(
c
o
m
p
a
r
e
N
u
m
e
r
i
c
(
));//
, , sort, .
, JavaScript,
. :
, a>b,
, a<b,
0, , ,
.
sort, JavaScript,
. , ,
.
, , .
, .
, , sort , ,
alert:
[1,2,15,2,0,8].sort(function(a,b){
alert(a+"<>"+b);
});
compareNumeric
compareNumeric - .
functioncompareNumeric(a,b){
returnab;
}
sort, , a>b,
, , 0, .
reverse
arr.reverse()
vararr=[1,2,3];
arr.reverse();
alert(arr);//3,2,1
concat
arr.concat(value1, value2, valueN) ,
arr, value1,value2,...valueN.
:
vararr=[1,2];
varnewArr=arr.concat(3,4);
alert(newArr);//1,2,3,4
concat .
concat , concat .
:
vararr=[1,2];
varnewArr=arr.concat([3,4],5);//,arr.concat(3,4,5)
alert(newArr);//1,2,3,4,5
indexOf/lastIndexOf
IE8-. ES5-shim
arr.indexOf(searchElement[, fromIndex])
arr 1, .
searchElement
fromIndex, . .
===.
:
vararr=[1,0,false];
alert(arr.indexOf(0));//1
alert(arr.indexOf(false));//2
alert(arr.indexOf(null));//1
, indexOf
arr.lastIndexOf(searchElement[, fromIndex])
fromIndex, .
-:
indexOf/lastIndexOf
, . .
indexOf/lastIndexOf ,
for . , .
, : -
. - indexOf. !
,
, .
, "div", "a" "form":
varstore={};//
varitems=["div","a","form"];
for(vari=0;i<items.length;i++){
varkey=items[i];//
store[key]=true;//
}
, key, if(store[key]).
, .
, ,
.
Object.keys(obj)
, for..in.
,
Object.keys(obj) . , IE8-:
varuser={
name:"",
age:30
}
varkeys=Object.keys(user);
alert(keys);//name,age
:
push/pop, shift/unshift, splice .
join/split .
sort .
.
reverse .
concat .
indexOf/lastIndexOf ( IE8-).
95% , .
Array Array Mozilla Developer Network .
: 5
className, ,
:
varobj={
className:'openmenu'
}
addClass(obj,cls), cls,
:
addClass(obj,'new');//obj.className='openmenunew'
addClass(obj,'open');//()
addClass(obj,'me');//obj.className='openmenunewme'
alert(obj.className);//"openmenunewme"
P.S. .
.
border-left-width borderLeftWidth
: 3
camelize(str), my-short-string
myShortString.
, , .
:
camelize("backgroundcolor")=='backgroundColor';
camelize("liststyleimage")=='listStyleImage';
camelize("webkittransition")=='WebkitTransition';
CSS.
P.S. charAt, split toUpperCase.
.
removeClass
: 5
className, , :
varobj={
className:'openmenu'
};
removeClass(obj,cls), cls, :
removeClass(obj,'open');//obj.className='menu'
removeClass(obj,'blabla');//()
P.S. .
:
obj={
className:'mymenumenu'
};
removeClass(obj,'menu');
alert(obj.className);//'my'
.
.
: 4
filterRangeInPlace(arr,a,b), arr
a..b. , aarr[i]b.
.
:
arr=[5,3,8,1];
filterRangeInPlace(arr,1,4);//1..4
alert(arr);//:[3,1]
: 5
?
vararr=[5,2,1,10,8];
//?
alert(arr);//8,5,2,1,10
: 5
arr. arrSorted , .
.
vararr=["HTML","JavaScript","CSS"];
//......
alert(arrSorted);//CSS,HTML,JavaScript
alert(arr);//HTML,JavaScript,CSS()
: 3
sort , .
vararr=[1,2,3,4,5];
arr.sort();
alert(arr);//,[3,5,1,2,4]
: 5
, people age.
:
varvasya={name:"",age:23};
varmasha={name:"",age:18};
varvovochka={name:"",age:6};
varpeople=[vasya,masha,vovochka];
......
//people:[vovochka,masha,vasya]
alert(people[0].age)//6
: 5
, ,
. , null.
, , next :
varlist={
value:1,
next:{
value:2,
next:{
value:3,
next:{
value:4,
next:null
}
}
}
};
:
varlist={value:1};
list.next={value:2};
list.next.next={value:3};
list.next.next.next={value:4};
, ,
, , .
.
:
1. printList(list), ,
.
2. printList(list) .
3. printReverseList(list),
, . 4,3,2,1
4. printReverseList(list), , .
?
: 3
, , .
:
aclean(arr), , .
:
vararr=["","","","","","",""];
alert(aclean(arr));//",,"",,"
, .
.
: 3
arr .
unique(arr), ,
arr.
:
functionunique(arr){
/**/
}
varstrings=["","","","",
"","","","","8()"
];
alert(unique(strings));//,,8()
:
JavaScript ,
IE8- ES5-shim
forEach
arr.forEach(callback[, thisArg])
callback.
callback(item,i,arr):
item .
i .
arr , .
:
vararr=["","",""];
arr.forEach(function(item,i,arr){
alert(i+":"+item+"(:"+arr+")");
});
filter
arr.filter(callback[, thisArg])
, arr,
callback(item,i,arr) true.
:
vararr=[1,1,2,2,3];
varpositiveArr=arr.filter(function(number){
returnnumber>0;
});
alert(positiveArr);//1,2,3
map
arr.map(callback[, thisArg])
, callback(item,i,arr)
arr.
:
varnames=['HTML','CSS','JavaScript'];
varnameLengths=names.map(function(name){
returnname.length;
});
//
alert(nameLengths);//4,3,10
every/some
.
arr.every(callback[, thisArg])
arr.
arr.some(callback[, thisArg])
arr.
vararr=[1,1,2,2,3];
functionisPositive(number){
returnnumber>0;
}
alert(arr.every(isPositive));//false,
alert(arr.some(isPositive));//true,
reduce/reduceRight
arr.reduce(callback[, initialValue])
.
. ,
,
.
reduce - ,
. .
callback ,
.
callback(previousValue,currentItem,index,arr):
previousValue , .
currentItem , -.
index .
arr .
callback, initialValue.
, previousValue initialValue, reduce
, , .
reduce .
, .
:
vararr=[1,2,3,4,5]
//,
//
varresult=arr.reduce(function(sum,current){
returnsum+current;
},0);
alert(result);//15
, .
sum , ,
( reduce).
, ,
, .
sum
current
10
10
15
, .
, reduce function(sum,current,i,
array), i arr, .
, , initialValue arr.reduce:
vararr=[1,2,3,4,5]
//0
varresult=arr.reduce(function(sum,current){
returnsum+current
});
alert(result);//15
! , initialValue
, .
, .
arr.reduceRight
, -:
:
forEach .
filter .
every/some .
map .
reduce/reduceRight .
,
for.
map
: 5
, :
vararr=["","","",""];
vararrLength=[];
for(vari=0;i<arr.length;i++){
arrLength[i]=arr[i].length;
}
alert(arrLength);//4,5,2,5
: , map.
: 2
, : arr=[1,2,3,4,5].
getSums(arr), .
, getSums(arr) ,
arr .
:
arr=[1,2,3,4,5]
getSums(arr)=[1,1+2,1+2+3,1+2+3+4,1+2+3+4+5]=[1,3,6,10,15]
: getSums([2,1,0,1])=[2,3,3,2].
.
arr.reduce.
.
arguments
JavaScript .
:
functiongo(a,b){
alert("a="+a+",b="+b);
}
go(1);//a=1,b=undefined
go(1,2);//a=1,b=2
go(1,2,3);//a=1,b=2,
JavaScript
,
, :
functionlog(a){
...
}
functionlog(a,b,c){
...
}
log(a);//
log(a,b,c);//
. JavaScript
.
log,
.
, - .
log .
, ?
- arguments
arguments, . ,
sayHi(a,b,c).
arguments
JavaScript - arguments -
.
arguments .
:
functionf(x){
arguments[0]=5;//x
alert(x);//5
}
f(1);
:
functionf(x){
x=5;
alert(arguments[0]);//5,x
}
f(1);
.
:
functionf(x){
"usestrict";//
arguments[0]=5;
alert(x);//5,1!""arguments
}
f(1);
,
, arguments.
arguments
Array arguments. :
functionsayHi(){
vara=arguments.shift();//!!
}
sayHi(1);
, arguments Array.
, , length.
. , .
, arguments, :
varargs=[];
for(vari=0;i<arguments.length;i++){
args[i]=arguments[i];
}
varvasya={
age:21,
name:'',
surname:''
};
varuser={
isAdmin:false,
isEmailConfirmed:true
};
varstudent={
university:'Myuniversity'
};
//vasyauserstudent
copy(vasya,user,student);
alert(vasya.isAdmin);//false
alert(vasya.university);//Myuniversity
user:
//
varuserClone=copy({},user);
, ,
user.
,
- . , .
:
functioncopy(){
vardst=arguments[0];
for(vari=1;i<arguments.length;i++){
vararg=arguments[i];
for(varkeyinarg){
dst[key]=arg[key];
}
}
returndst;
}
copy , , dst.
:
functioncopy(dst){
//
for(vari=1;i<arguments.length;i++){
vararg=arguments[i];
for(varkeyinarg){
dst[key]=arg[key];
}
}
returndst;
}
||
, ,
undefined.
, , .
||.
, showWarning, , .
width, height, title contents,
:
functionshowWarning(width,height,title,contents){
width=width||200;//width,width=200
height=height||100;//height,height=100
title=title||"";
//...
}
,
false. , width=0 width=null,
.
, width===undefined?
, :
functionshowWarning(width,height,title,contents){
if(width===undefined)width=200;
if(height===undefined)height=100;
if(title===undefined)title="";
//...
}
arguments.callee
NFE arguments.callee
, usestrict .
, , ,
.
(NFE).
JavaScript arguments ,
arguments.callee , .
:
functionf(){
alert(arguments.callee===f);//true
}
f();
:
//NFE
varfactorial=functionf(n){
r
e
t
u
r
n
n
=
=
1
?
1
:
n
*
f
(
n
1
);
};
//arguments.callee
varfactorial=function(n){
e
t
u
r
n
n
=
=
1
?
1
:
n
*
a
r
g
u
m
e
n
t
s
.
c
a
l
l
e
e
(
n
1
)
;
r
};
, .
arguments.callee.caller
arguments.callee.caller , .
, usestrict , arguments.callee.
arguments.caller. ,
-. arguments.callee.caller ,
usestrict, .
f1();
functionf1(){
alert(arguments.callee.caller);//null,
f2();
}
functionf2(){
alert(arguments.callee.caller);//f1,,
f3();
}
functionf3(){
alert(arguments.callee.caller);//f2,,
}
,
arguments.
- : f(width=100,
height=200), , , .
, ,
, .
. ,
, -
, .
JavaScript ,
.
:
functionshowWarning(options){
varwidth=options.width||200;//
varheight=options.height||100;
vartitle=options.title||"";
//...
}
showWarning({
. ,
:
showWarning({
contents:""//!
});
:
showWarning(null,null,"!");
//"null,null?,"
, ?
:
varopts={
width:400,
height:200,
contents:""
};
showWarning(opts);
opts.contents="";
showWarning(opts);//,
JavaScript-.
, , arguments.
, , ,
length, .
arguments.callee ,
arguments.callee.caller, , .
, usestrict .
, , false,
||.
, , ,
, arguments ,
options.
, , options,
:
functionshowMessage(text,options){
//text,options
}
-undefined
: 5
undefined?
functionf(x){
//....
//1,,0
}
f(undefined);//1
f();//0
: 5
sum(...), :
sum()=0
sum(1)=1
sum(1,2)=3
sum(1,2,3)=6
sum(1,2,3,4)=10
JavaScript Date
Date :
newDate()
Date :
varnow=newDate();
alert(now);
newDate(milliseconds)
Date, (1/1000 ),
1 1970 GMT+0.
//2401.01.1970GMT+0
varJan02_1970=newDate(3600*24*1000);
alert(Jan02_1970);
newDate(datestring)
, Date.parse(. )
.
newDate(year,month,date,hours,minutes,seconds,ms)
, .
. , hours
, date .
:
year 4 .
month 0.
:
newDate(2011,0,1,0,0,0,0);////12011,00:00:00
newDate(2011,0,1);//,/0
:
vardate=newDate(2011,0,1,2,3,4,567);
alert(date);//1.01.2011,02:03:04.567
- Date :
getFullYear()
( 4 )
getMonth()
, 0 11.
getDate()
, 1 31.
getHours(),getMinutes(),getSeconds(),getMilliseconds()
.
getYear(), getFullYear()
getYear(). -
, - . , JavaScript.
. getFullYear().
:
getDay()
. JavaScript ,
0() 6().
, , .
UTC- , , , ..
GMT+0 (UTC): getUTCFullYear(), getUTCMonth(), getUTCDay(). , "get"
"UTC".
UTC, :
//
vardate=newDate();
//
alert(date.getHours());
//?
//GMT+0
alert(date.getUTCHours());
, UTC-:
getTime()
, 1 1970 GMT+0, ,
newDate(milliseconds).
getTimezoneOffset()
UTC-, .
alert(newDate().getTimezoneOffset());//GMT160
setFullYear(year[,month,date])
setMonth(month[,date])
setDate(date)
setHours(hour[,min,sec,ms])
setMinutes(min[,sec,ms])
setSeconds(sec[,ms])
setMilliseconds(ms)
setTime(milliseconds)( 01.01.1970 UTC)
, setTime(), UTC-, : setUTCHours().
, ,
, setHours. - , . :
vartoday=newDate;
today.setHours(0);
alert(today);//,0
today.setHours(0,0,0,0);
alert(today);//,00:00:00.
Date. ,
( 32 ),
.
a
r
d
=
n
e
w
D
a
t
e
(
2
0
1
3
,
0
,
3
2
);//322013?!?
v
alert(d);//...12013!
.
, 2 28 2011. , 2 ,
1 , . .
. Date:
vard=newDate(2011,1,28);
d.setDate(d.getDate()+2);
alert(d);//2,2011
,
. , 70 :
vard=newDate();
d.setSeconds(d.getSeconds()+70);
alert(d);//
, . :
vard=newDate;
d.setDate(1);//
alert(d);
d.setDate(0);//,
alert(d);
vard=newDate;
d.setDate(1);//
alert(d);
,
Date , :
alert(+newDate)//+date,:+date.valueOf()
: , Date
, .
:
varstart=newDate;//
//
for(vari=0;i<100000;i++){
vardoSomething=i*i*i;
}
varend=newDate;//
alert(""+(endstart)+"ms");
, , .
, ?
, :
functionwalkIn(arr){
for(varkeyinarr)arr[i]++
}
functionwalkLength(arr){
for(vari=0;i<arr.length;i++)arr[i]++;
}
, , walkIn, walkLength
. , - .
,
. . 100 ,
1000
, :
vararr=[];
for(vari=0;i<1000;i++)arr[i]=0;
functionwalkIn(arr){
for(varkeyinarr)arr[i]++;
}
functionwalkLength(arr){
for(vari=0;i<arr.length;i++)arr[i]++;
}
functionbench(f){
vardate=newDate();
for(vari=0;i<10000;i++)f(arr);
returnnewDate()date;
}
alert('walkIn:'+bench(walkIn)+'');
alert('walkLength:'+bench(walkLength)+'');
, bench(walkIn) -
() , .
? , , .
,
.
vararr=[];
for(vari=0;i<1000;i++)arr[i]=0;
functionwalkIn(arr){
for(varkeyinarr)arr[i]++;
}
functionwalkLength(arr){
for(vari=0;i<arr.length;i++)arr[i]++;
}
functionbench(f){
vardate=newDate();
for(vari=0;i<1000;i++)f(arr);
returnnewDate()date;
}
//bench,
vartimeIn=0,
timeLength=0;
for(vari=0;i<100;i++){
timeIn+=bench(walkIn);
timeLength+=bench(walkLength);
}
alert('walkIn:'+timeIn+'');
alert('walkLength:'+timeLength+'');
performance.now()
( IE9-) performance.now()
, . , ,
HTML-, .
, .
, <head>, ,
, , HTML.
, 3
( !),
.
console.time() console.timeEnd()
:
console.time() .
console.timeEnd()
.
"" ,
.
walkIn, walkLength , All Benchmarks
:
vararr=[];
for(vari=0;i<1000;i++)arr[i]=0;
functionwalkIn(arr){
for(varkeyinarr)arr[i]++;
}
functionwalkLength(arr){
for(vari=0;i<arr.length;i++)arr[i]++;
}
functionbench(f){
for(vari=0;i<10000;i++)f(arr);
}
console.time("AllBenchmarks");
console.time("walkIn");
bench(walkIn);
console.timeEnd("walkIn");
console.time("walkLength");
bench(walkLength);
console.timeEnd("walkLength");
console.timeEnd("AllBenchmarks");
, .
, !
JavaScript , :
1. , arr.length,
.
2. , ,
, , .
3. , ,
.
4. , ,
, ,
.
,
JavaScript ( ) ,
JavaScript- , , .
, IE10-, Ecma 402
.
date.toLocaleString(,),
. , , ,
.
, () :
vardate=newDate(2014,11,31,12,30,0);
varoptions={
era:'long',
year:'numeric',
month:'long',
day:'numeric',
weekday:'long',
timezone:'UTC',
hour:'numeric',
minute:'numeric',
second:'numeric'
};
alert(date.toLocaleString("ru",options));//,312014...12:30:00
alert(date.toLocaleString("enUS",options));//Wednesday,December31,2014AnnoDomini12:30:00PM
Intl: JavaScript,
.
:
toString(), toDateString(), toTimeString()
, ,
. . toString
, toDateString() toTimeString() .
vard=newDate();
alert(d.toString());//,'WedJan26201116:40:50GMT+0300'
toUTCString()
, toString(), UTC.
toISOString()
ISO .
, IE8-.
vard=newDate();
alert(d.toISOString());//,'20110126T13:51:50.417Z'
-,
, Moment.JS .
, Date.parse
, IE9+, ISO 8601 Extended.
: YYYYMMDDTHH:mm:ss.sssZ, :
YYYYMMDD --.
T .
HH:mm:ss.sss : ---.
'Z' +hh:mm, Z, UTC.
, UTC, Safari ,
.
, YYYYMMDD YYYYMM YYYY.
Date.parse(str) str
. , Date.parse NaN.
:
varmsUTC=Date.parse('20120126T13:51:50.417Z');//UTC
alert(msUTC);//1327571510417()
07:00GMT:
varms=Date.parse('20120126T13:51:50.41707:00');
alert(ms);//1327611110417()
IE8 EcmaScript 5 , ,
IE8-, . , .
, , IE:
varms=Date.parse("January26,201113:51:50");
alert(ms);
IE MSDN Date.parse
, . IE8-,
Date.parse, , es5-shim .
Date.now()
Date.now() .
, +newDate(),
, .
,
. -, , , JavaScript.
JavaScript : Date .
, . Date Date
.
.
( getDay()) ( ).
Date , . .
Date , 1
1970 UTC. ,
.
Date.now(),
Date( IE8-)
performance.now()( IE9-), 1000 .
: 5
Date : 20 2012 , 3 12 .
. .
: 5
getWeekDay(date),
'', '', ''.
:
vardate=newDate(2012,0,3);//32012
alert(getWeekDay(date));//''
: 5
, getLocalDay(date) date.
, .. 1,
2, , 7.
vardate=newDate(2012,0,3);//32012
alert(getLocalDay(date));//,2
: 4
getDateAgo(date,days), , days
date.
, 2 2015:
vardate=newDate(2015,0,2);
alert(getDateAgo(date,1));//1,(12015)
alert(getDateAgo(date,2));//31,(312014)
alert(getDateAgo(date,365));//2,(22014)
P.S. : date.
.
?
: 5
getLastDayOfMonth(year,month), .
:
year 4- , 2012.
month 0 11.
, getLastDayOfMonth(2012,1)=29( , ).
.
?
: 5
getSecondsToday() ,
.
, 10:00 / , :
getSecondsToday()==36000//(3600*10)
, ..
.
?
: 5
getSecondsToTomorrow() ,
.
, 23:00, :
getSecondsToTomorrow()==3600
P.S. , ..
.
..
: 3
formatDate(date), date ..:
:
vard=newDate(2014,0,30);//302014
alert(formatDate(d));//'30.01.14'
P.S. , , 1 2001
01.01.01, 1.1.1.
.
: 4
formatDate(date), date:
date , "".
date , "n.".
, "m.".
"..:".
:
functionformatDate(date){/**/}
alert(formatDate(newDate(newDate1)));//""
alert(formatDate(newDate(newDate30*1000)));//"30."
alert(formatDate(newDate(newDate5*60*1000)));//"5."
alert(formatDate(newDate(newDate86400*1000)));//"..:"
,
JavaScript,
.
.
JavaScript .
, .
.
, - .
, , function,
.
JavaScript
, (globalobject).
window. window
,
.
, Node.JS, ,
,
"window".
, , ,
window.
:
vara=5;//varwindow.a
alert(window.a);//5
window:
window.a=5;
alert(a);//5
:
1. , .
Function
Declaration, var.
window.
, Function Declaration, ,
undefined.
2. , .
(=) ,
, undefined.
:
//,:
//window={f:function,a:undefined,g:undefined}
vara=5;
/
w
i
n
d
o
w
=
{
f
:
f
u
n
c
t
i
o
n
,
a
:
5
,g:undefined}
/
functionf(arg){/*...*/}
//window={f:function,a:5,g:undefined},f
varg=function(arg){/*...*/};
/
w
i
n
d
o
w
=
{
f
:
f
u
n
c
t
i
o
n
,
a
:
5
,
g
:
f
u
n
c
t
i
o
n
}
/
, , window,
, :
l
e
r
t
(
"
a
"
i
n
w
i
n
d
o
w
)
;
/
/
t
r
u
e
,..window.a
a
l
e
r
t
(
a
)
;
/
/
u
n
d
e
f
i
n
e
d
,
a
a
l
e
r
t
(
f
)
;
/
/
f
u
n
c
t
i
o
n
.
.
.,
l
e
r
t
(
g
)
;
/
/
u
n
d
e
f
i
n
e
d
,..,FunctionDeclaration
a
vara=5;
functionf(){/*...*/}
varg=function(){/*...*/};
JavaScript var:
a=5;
alert(a);//5
, :
alert(a);//error,aisnotdefined
a=5;
, , , var.
for,if...
, for,while,if, ,
.
JavaScript :
a
r
i;
v
{
i=5;
}
:
i=5;
{
v
a
ri;
}
f
o
r
(
v
a
ri=0;i<5;i++){}
:
a
r
i
;
v
for(i=0;i<5;i++){}
, ,
.
,
var :
vari=10;
for(vari=0;i<20;i++){
...
}
vari=5;
var , .
var : .
.
var, .
, var.
2. - window. IE8-:
<script>
//,window
window.recurse=function(times){
if(times!==0)recurse(times1);
}
recurse(13);
</script>
- , window.recurse=
.... .
IE8! IE9 . ,
- 95% ,
5% IE8 .
, :
1. , FunctionDeclaration,
.
2. , undefined. ,
.
Window
: 5
?
if("a"inwindow){
vara=1;
}
alert(a);
Window 2
: 5
( a var)?
if("a"inwindow){
a=1;
}
alert(a);
Window 3
: 5
( a var, )?
if("a"inwindow){
a=1;
}
vara;
alert(a);
,
, , , ,
. .
LexicalEnvironment, .
.
LexicalEnvironment, ,
. ,
, , , .
window, LexicalEnvironment , .
, , :
functionsayHi(name){
varphrase=","+name;
alert(phrase);
}
sayHi('');
:
1. , ,
LexicalEnvironment .
name phrase:
functionsayHi(name){
//LexicalEnvironment={name:'',phrase:undefined}
varphrase=","+name;
alert(phrase);
}
sayHi('');
2. .
phrase, ,
, LexicalEnvironment.phrase :
functionsayHi(name){
//LexicalEnvironment={name:'',phrase:undefined}
varphrase=","+name;
//LexicalEnvironment={name:'',phrase:','}
alert(phrase);
}
sayHi('');
3.
. .
,
.
ECMA-262, , :
VariableEnvironment LexicalEnvironment.
, .
LexicalEnvironment,
.
ECMA-262, 10.2-10.5 13.
, :
varuserName="";
functionsayHi(){
alert(userName);//""
}
, ,
LexicalEnvironment, , .
window.
,
, [[Scope]].
, ,
JavaScript.
[[Scope]],
, .
window, :
sayHi.[[Scope]]=window
. , , ,
.
LexicalEnvironment
[[Scope]].
.
alert(userName) .
, .
:
[[Scope]] ,
.
LexicalEnvironment.
[[Scope]].
,
.
, [[Scope]],
. : .
,
.
. ,
.
, sayHi phrase :
varphrase='';
functionsay(name){
alert(phrase+','+name);
}
say('');//,(*)
phrase='';
say('');//,(**)
, .
, :
functionsayHiBye(firstName,lastName){
alert(","+getFullName());
alert(","+getFullName());
functiongetFullName(){
returnfirstName+""+lastName;
}
}
sayHiBye("","");//,;,
, , getFullName().
[[Scope]] , . :
getFullName.[[Scope]]=sayHiBye
varphrase='';
functionsay(){
functiongo(){
alert(phrase);//
}
go();
}
,
.
,
.
-,
.
makeCounter :
functionmakeCounter(){
varcurrentCount=1;
returnfunction(){//(**)
returncurrentCount++;
};
}
varcounter=makeCounter();//(*)
//
alert(counter());//1
alert(counter());//2
alert(counter());//3
//,
varcounter2=makeCounter();
alert(counter2());//1
, counter counter2,
.
? , currentCount, .
:
1. (*) makeCounter(). LexicalEnvironment
. varcurrentCount,
. undefined, , ,
1:
functionmakeCounter(){
//LexicalEnvironment={currentCount:undefined}
varcurrentCount=1;
//LexicalEnvironment={currentCount:1}
returnfunction(){//[[Scope]]>LexicalEnvironment(**)
returncurrentCount++;
};
}
varcounter=makeCounter();//(*)
2. makeCounter() (**).
[[Scope]] LexicalEnvironment.
3. makeCounter() (**)
counter(*).
.
, counter, :
function(){//[[Scope]]>{currentCount:1}
returncurrentCount++;
};
, .
. :
varcounter=makeCounter();
varcounter2=makeCounter();
alert(counter());//1
alert(counter());//2
alert(counter());//3
a
l
e
r
t
(
c
o
u
n
t
e
r
2
(
)
)
;
/
/
1
,
, makeCounter
LexicalEnvironment, currentCount,
[[Scope]].
JavaScript , , :
functionf(){}
f.test=5;
alert(f.test);
.
. , .
.
. .
,
.
, :
functionmakeCounter(){
functioncounter(){
returncounter.currentCount++;
};
counter.currentCount=1;
returncounter;
}
varcounter=makeCounter();
alert(counter());//1
alert(counter());//2
.
, ,
, , .
, :
varcounter=makeCounter();
alert(counter());//1
counter.currentCount=5;
alert(counter());//5
, , .
,
. JavaScript
.
, .
, Wikipedia
. , + .
, JavaScript .
, , ,
.
.
.
?
, !. ,
?
JavaScript :
1.
LexicalEnvironment. .
, window.
2. [[Scope]],
LexicalEnvironment, .
3. ,
, LexicalEnvironment .
,
, .
say ?
: 5
, sayHi(''); - , ?
say('');//??
varphrase='';
functionsay(name){
alert(name+","+phrase);
}
?
: 5
?
varvalue=0;
functionf(){
if(1){
value=true;
}else{
varvalue=false;
}
alert(value);
}
f();
value?
P.S. , varvalue=false var?
var window
: 5
? ?
functiontest(){
alert(window);
varwindow=5;
alert(window);
}
test();
: 4
? ?
vara=5
(function(){
alert(a)
})()
P.S. ! ! P.P.S. , ! ,
.
: 4
currentCount
currentCount ?
functionmakeCounter(){
varcurrentCount=1;
returnfunction(){
varcurrentCount;
//currentCount(1)?
};
}
: 5
, currentCount makeCounter?
varcurrentCount=1;
functionmakeCounter(){
returnfunction(){
returncurrentCount++;
};
}
varcounter=makeCounter();
varcounter2=makeCounter();
alert(counter());//?
alert(counter());//?
alert(counter2());//?
alert(counter2());//?
, newFunction,
a :
vara=1;
functiongetFunc(){
vara=2;
varfunc=newFunction('','alert(a)');
returnfunc;
}
g
e
t
F
u
n
c
(
)
(
)
;
/
/
1,window
:
vara=1;
functiongetFunc(){
vara=2;
varfunc=function(){alert(a);};
returnfunc;
}
e
t
F
u
n
c
(
)
(
)
;
/
/
2
,LexicalEnvironmentgetFunc
g
,
JavaScript.
newFunction, , .
, .
( newFunction),
, .
,
.
, JavaScript
, ,
, ,
.
, varuserName, vara(
, ), ,
, , . .
newFunction ,
userName , .
, new
Function, ,
.
newFunction- .
, newFunction, -
,
, :
varsum=newFunction('a,b','returna+b;');
vara=1,b=2;
alert(sum(a,b));//3
, newFunction, [[Scope]]
, window.
. ,
, JavaScript .
.
. ,
.
-
.
, :
functionmakeCounter(){
varcurrentCount=1;
returnfunction(){
returncurrentCount++;
};
}
varcounter=makeCounter();
//,
alert(counter());//1
alert(counter());//2
alert(counter());//3
, . ,
1
, , .
:
functionmakeCounter(){
varcurrentCount=1;
return{//
getNext:function(){
returncurrentCount++;
},
set:function(value){
currentCount=value;
},
reset:function(){
currentCount=1;
}
};
}
varcounter=makeCounter();
alert(counter.getNext());//1
alert(counter.getNext());//2
counter.set(5);
alert(counter.getNext());//5
makeCounter , :
getNext() , , counter().
set(value) .
reset() .
[[Scope]] () .
currentCount.
+
, : counter(),
.
, ,
counter.getNext().
!
functionmakeCounter(){
varcurrentCount=1;
//
functioncounter(){
returncurrentCount++;
}
//...!
counter.set=function(value){
currentCount=value;
};
counter.reset=function(){
currentCount=0;
};
returncounter;
}
varcounter=makeCounter();
alert(counter());//1
alert(counter());//2
counter.set(5);
alert(counter());//5
, ? , .
JavaScript-. ,
jQuery jQuery (
$),
jQuery(...), , jQuery.type(123)
.
: 4
sum, : sum(a)(b)=a+b.
, , ( ). :
sum(1)(2)=3
sum(5)(1)=4
: 5
,
. :
1. .
2. .
JavaScript,
:
: varbuffer=makeBuffer();.
makeBuffer buffer, buffer(value)
, buffer()
.
:
functionmakeBuffer(){/**/}
varbuffer=makeBuffer();
//
buffer('');
buffer('');
buffer('!');
//
alert(buffer());//!
varbuffer=makeBuffer();
buffer(0);
buffer(1);
buffer(0);
alert(buffer());//'010'
.
.
: 5
buffer.clear(),
:
functionmakeBuffer(){
......
}
varbuffer=makeBuffer();
buffer("");
buffer("");
alert(buffer());//
buffer.clear();
alert(buffer());//""
: 5
:
varusers=[{
name:"",
surname:'',
age:20
},{
name:"",
surname:'',
age:25
},{
name:"",
surname:'',
age:18
}];
:
//name(,,)
users.sort(function(a,b){
returna.name>b.name?1:1;
});
//age(,,)
users.sort(function(a,b){
returna.age>b.age?1:1;
});
, :
users.sort(byField('name'));
users.forEach(function(user){
alert(user.name);
});//,,
users.sort(byField('age'));
users.forEach(function(user){
alert(user.name);
});//,,
, , sortfunction...
byField(...)
byField(field), sort
field, .
: 5
1. filter(arr,func), arr ,
arr, func true.
2. : inBetween(a,b) a,b, inArray([...])
[...]. :
filter(arr,inBetween(3,6)) 3 6,
filter(arr,inArray([1,2,3])) ,
.
, :
/*..filter,inBetween,inArray*/
vararr=[1,2,3,4,5,6,7];
alert(filter(arr,function(a){
returna%2==0
}));//2,4,6
alert(filter(arr,inBetween(3,6)));//3,4,5,6
alert(filter(arr,inArray([1,2,10])));//1,2
: 5
- shooters. ,
:
functionmakeArmy(){
varshooters=[];
for(vari=0;i<10;i++){
varshooter=function(){//
alert(i);//
};
shooters.push(shooter);
}
returnshooters;
}
vararmy=makeArmy();
army[0]();//10,0
army[5]();//10...
//..100,1,2...9
? , .
.
.
.
, , , .
. : ,
, - ..
?
, , - .
, , (
), :
hello.js
//
varmessage="";
//
functionshowMessage(){
alert(message);
}
//
showMessage();
.
message showMessage.
, . , ,
.
, , hello.js .
,
, .
, :
<script>
varmessage=",";
</script>
<scriptsrc="hello.js"></script>
<button></button>
<script>
//...
alert(message);//""
</script>
, "hello.js" , .
message "".
hello.js, .
hello.js, , , ,
message hello.js .
, - ,
, .
, .
hello.js, :
(function(){
//
varmessage="";
//
functionshowMessage(){
alert(message);
}
//
showMessage();
})();
.
, , .
?
:
(function(){
alert(",,");
//...
}());
, .
, , :
function(){
//
}();
, , function
, FunctionDeclaration, .
, , :
functionwork(){
//...
}();//syntaxerror
, FunctionExpression.
:
function , FunctionDeclaration.
function , , Function
Expression.
, FunctionExpression,
JavaScript .
, :
+function(){
alert('');
}();
!function(){
alert('');
}();
.
? , ,
, .
, , Lodash
jQuery
, lodash( _),
, , :
_.defaults(src,dst1,dst2...) src dst1, dst2
, .
_.cloneDeep(obj) obj,
.
_.size(obj) , :
1 .
,
:
<p></p>
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.2.0/lodash.js"></script>
<p><code>_.defaults()</code>.</p>
<script>
varuser={
name:''
};
_.defaults(user,{
name:'',
employer:''
});
alert(user.name);//
alert(user.employer);//
alert(_.size(user));//2
</script>
, , ,
.
:
;(function(){
//lodash
functionlodash(value){
//...
}
//
varversion='2.4.1';
//...
//size,
functionsize(collection){
returnObject.keys(collection).length;
}
//lodashsize,
lodash.size=size
//lodash.defaults=...
//lodash.cloneDeep=...
//""lodash
window._=lodash;//,
}());
:
1. , , .
2. window , .
, window lodash, .
, , ,
.
?
; ,
.
, JS- (, ,
, ), ,
.
, a.js:
vara=5
lib.js:
(function(){
//
})()
:
vara=5
//
(function(){
//...
})();
,
. vara=5(function...), 5
.
, .
lodash ; , .
return
-, return:
varlodash=(function(){
varversion;
functionassignDefaults(){...}
return{
defaults:function(){}
}
})();
, , function(){...} ,
, Function Expression.
, , , ,
.
, .
.
, defaults assignDefaults.
, , ,
. ,
.
. ,
- .
JavaScript
JavaScript . , ,
.
, ? ?
.
JavaScript
JavaScript (.
reachability).
1. , :
, ,
,
.
.
. .
2. ,
.
(. Garbage collection, GC), ,
.
. ,
, , ,
.
, ,
,
, .
, .
: , .
.
, , - .
, , :
varuser={
name:""
};
user=null;
{name:""} . .
: ,
.
, :
varvasya={};
varpetya={};
vasya.friend=petya;
petya.friend=vasya;
vasya=petya=null;
.
.
, , , .
.
, .
, :
functionmarry(man,woman){
woman.husband=man;
man.wife=woman;
return{
father:man,
mother:woman
}
}
varfamily=marry({
name:""
},{
name:""
});
marry , ,
.
family :
, name ,
, .
, :
deletefamily.father;
deletefamily.mother.husband;
, .
window, .
, , family.father ,
:
, - ,
.
family.father ,
.
. , family?
, , :
window.family=null;
, . ,
, , .
. ,
.
,
. , - .
.
.
. ,
, . .
. .
,
, , :
functionshowTime(){
alert(newDate());//
}
,
V8 , , A tour of V8: Garbage Collection .
, , ,
. , .
,
, [[Scope]].
:
.
:
functionf(){
varvalue=123;
functiong(){}//g
}
f();
value g . f()
, . ,
.
, value, :
functionf(){
varvalue=123;
functiong(){}
returng;
}
varg=f();//g
g.[[Scope]] ,
g. , value.
f() , , ,
, LexicalEnvironment
value:
functionf(){
varvalue=Math.random();
returnfunction(){};
}
//3,,
//value
vararr=[f(),f(),f()];
LexicalEnvironment , .
g:
functionf(){
varvalue=123;
functiong(){}
returng;
}
varg=f();//g
//f()
g=null;//..
V8
JS- .
,
, .
value . .
V8 (Chrome, Opera) ,
!
Chrome. ,
alert(value).
functionf(){
varvalue=Math.random();
functiong(){
debugger;//alert(value);!
}
returng;
}
varg=f();
g();
! g. ,
.
,
, :
varvalue="";
functionf(){
varvalue="";
functiong(){
debugger;//alert(value);!
}
returng;
}
varg=f();
g();
. Chrome/Opera,
!
, V8, , , -
. , ,
.
. ,
.
.
. - .
, ?
:
functionsumTo(n){//1+2+...+n
varresult=0;
for(vari=1;i<=n;i++){
result+=i;
}
returnresult;
}
functionsumToRec(n){//sumToRec(n)=n+SumToRec(n1)
returnn==1?1:n+sumToRec(n1);
}
vartimeLoop=performance.now();
for(vari=1;i<1000;i++)sumTo(1000);//
timeLoop=performance.now()timeLoop;
vartimeRecursion=performance.now();
for(vari=1;i<1000;i++)sumToRec(1000);//
timeRecursion=performance.now()timeRecursion;
alert(""+(timeRecursion/timeLoop)+"");
, , 2-10
.
, . ,
. ,
. 2-10 (
, ) , .
,
JavaScript . .
with
with
.
JavaScript . usestrict ,
, , ,
.
:
with(obj){
......
}
with obj,
with.
, obj:
vara=5;
varobj={
a:10
};
with(obj){
alert(a);//10,obj
}
, obj:
varb=1;
varobj={
a:10
};
with(obj){
alert(b);//1,window
}
obj.b, with.
with:
varobj={
weight:10,
size:{
width:5,
height:7
}
};
with(obj){
with(size){//sizeobj
alert(width*height/weight);//width,heightsize,weightobj
}
}
!
: size=>obj=>window.
with, ,
.
:
varobj={
a:10
}
with(obj){
a=20;
}
alert(obj.a);//20,
with?
.
1. JavaScript with, with
.
, with(obj) ,
obj, .
:
varobj={
weight:10
};
with(obj){
weight=20;//(1)
size=35;//(2)
}
alert(obj.size);
alert(window.size);
(2) , obj. ,
, window.size.
, , size window,
- LexicalEnvironment.
2. JavaScript with.
JavaScript . , Closure Compiler UglifyJS .
,
. with .
, , ( ), .
, .
3. , , - with
.
,
, with.
, , . fast
slow (!) with. with, ..
.
vari=0;
functionfast(){
i++;
}
functionslow(){
with(i){}
i++;
}
vartime=performance.now();
while(i<1000000)fast();
alert("with:"+(performance.now()time));
vartime=performance.now();
i=0;
while(i<1000000)slow();
alert("with:"+(performance.now()time));
with
with , :
/*
with(elem.style){
top='10px';
left='20px';
}
*/
vars=elem.style;
s.top='10px';
s.left='0';
, ,
.
with(obj){...} obj .
, , obj.
with . .
With +
: 5
?
functionf(){
alert(1)
}
varobj={
f:function(){
alert(2)
}
};
with(obj){
f();
}
With +
: 5
?
vara=1;
varobj={
b:2
};
with(obj){
varb;
alert(a+b);
}
- ,
.
, this
.
().
-, :
varuser={
name:'',
//
sayHi:function(){
alert('!');
}
};
//
user.sayHi();
- . ,
:
varuser={
name:''
};
user.sayHi=function(){//
alert('!');
};
//:
s
e
r
.
s
a
y
H
i
(
)
;
this
. ,
user.sayHi() .
this.
this , , :
varuser={
name:'',
sayHi:function(){
l
e
r
t
(
t
h
i
s
.
n
a
m
e
);
a
}
};
user.sayHi();//sayHiuser
user.sayHi() this
user.
this sayHi , user:
...
sayHi:function(){
a
l
e
r
t
(
u
s
e
r
.
n
a
m
e);
}
...
, . ,
admin=user, user -
:
varuser={
name:'',
sayHi:function(){
l
e
r
t
(
u
s
e
r
.
n
a
m
e
);//
a
}
};
varadmin=user;
user=null;
admin.sayHi();//!sayHi,!
this, ,
.
this , -
:
varuser={
name:'',
sayHi:function(){
showName(this);//showName
}
};
functionshowName(namedObj){
alert(namedObj.name);
}
user.sayHi();//
this
this. ,
.
this .
, , , :
functionsayHi(){
a
l
e
r
t
(
t
h
i
s
.
f
i
r
s
t
N
a
m
e);
}
, this. .
,
this:
varuser={firstName:""};
varadmin={firstName:""};
functionfunc(){
alert(this.firstName);
}
user.f=func;
admin.g=func;
//this:
user.f();//
admin.g();//
admin['g']();//(,)
, this , ,
.
this
this . func()
.
, .
this window, :
functionfunc(){
alert(this);//[objectWindow][objectglobal]
}
func();
.
usestrict this undefined:
functionfunc(){
"usestrict";
alert(this);//undefined(IE9)
}
func();
this, , , ,
.
this , .
this, ( ).
, :
varuser={
name:"",
hi:function(){alert(this.name);},
bye:function(){alert("");}
};
user.hi();//()
//user.hiuser.bye
(user.name==""?user.hi:user.bye)();//undefined
. this .
, , obj.method().
, , : .
() (, ).
, , .
, JavaScript ,
Reference Type .
base-name-strict, :
base ,
name ,
strict usestrict.
, (Reference Type) --.
, ,
:
() base name base.
base name ,
.
, ,
.
obj[method].
: 5
? ?
vararr=["a","b"];
arr.push(function(){
alert(this);
})
arr[2]();//?
: 2
?
varobj={
go:function(){alert(this)}
}
(obj.go)()
P.S. :)
this ?
: 3
(1) (2) , (3) (4):
"usestrict"
varobj,f;
obj={
go:function(){alert(this);}
};
obj.go();//(1)object
(obj.go)();//(2)object
(method=obj.go)();//(3)undefined
(obj.go||obj.stop)();//(4)undefined
? this.
this
: 5
alert ? ?
varname="";
varuser={
name:"",
export:this
};
alert(user.export.name);
this
: 5
alert ? ?
varname="";
varuser={
name:"",
export:function(){
returnthis;
}
};
alert(user.export().name);
this
: 5
alert ? ?
varname="";
varuser={
name:"",
export:function(){
return{
value:this
};
}
};
alert(user.export().value.name);
: 5
calculator :
read() prompt
sum()
mul()
varcalculator={
......
}
calculator.read();
alert(calculator.sum());
alert(calculator.mul());
: 2
ladder:
varladder={
step:0,
up:function(){//
this.step++;
},
down:function(){//
this.step;
},
showStep:function(){//
alert(this.step);
}
};
, , :
ladder.up();
ladder.up();
ladder.down();
ladder.showStep();//1
, , :
ladder.up().up().down().up().down().showStep();//1
, .
(chaining) , , jQuery.
: toString valueOf
,
. .
, .
:
alert(obj).
, .
if(obj) .
.
.
true, [] {}.
if({}&&[]){
alert("true!");//alert
}
, alert:
varuser={
firstName:''
};
alert(user);//[objectObject]
, . ,
"[objectObject]".
.
- .
toString, ,
.
varuser={
firstName:'',
o
S
t
r
i
n
g
:
function(){
t
return''+this.firstName;
}
};
alert(user);//
toString
toString .
. , ,
:
varobj={
toString:function(){
return123;
}
};
alert(obj);//123
, .
, , toString, :
alert([1,2]);//toString"1,2"
alert(newDate);//toString
alert(function(){});//toString
valueOf, toString:
varroom={
number:777,
valueOf:function(){returnthis.number;},
toString:function(){returnthis.number;}
};
a
l
e
r
t
(
+
r
o
o
m
)
;
/
/
7
7
7
,
v
a
l
u
e
O
f
e
l
e
t
e
r
o
o
m
.
v
a
l
u
e
O
f
;
/
/
v
a
l
u
e
O
f
d
l
e
r
t
(
+
r
o
o
m
)
;
/
/
7
7
7
,
t
o
S
t
r
i
n
g
valueOf ,
. .
valueOf
valueOf,
.
Date, :
alert(newDate());//toString:
alert(+newDate());//valueOf:,01.01.1970
, 15.2.4.4 , valueOf
. , (- !),
.
, toString valueOf.
. ,
- .
, ==:
varobj={
valueOf:function(){
return1;
}
};
alert(obj==true);//true
obj , ,
1==true.
, , ,
: true.
+:
varobj={
valueOf:function(){
return1;
}
};
alert(obj+"test");//1test
, :
vara={
valueOf:function(){
return"1";
}
};
varb={
valueOf:function(){
return"2";
}
};
alert(a+b);//"12"
alert(ab);//"1""2"=1
: Date
Date, , .
+ valueOf.
, valueOf ( ),
toString, .
valueOf, valueOf. a+b .
Date valueOf toString. + Date toString
( valueOf).
:
//,
alert(newDate+"");//""
//,*/,
alert(+newDate);//
Java-
Java ( JavaScript, , )
, newBoolean(true/false), newBoolean(true).
JavaScript ,
.
, ,
. ,
JavaScript, :
varvalue=newBoolean(false);
if(value){
alert(true);//!
}
alert? if false :
varvalue=newBoolean(false);
alert(value);//false,..
if(value){
alert(true);//..alertif?!?
}
, newBoolean , .
true, .
alert, ,
"false".
JavaScript newBoolean/String/Number ,
,
, Boolean(val)===!!val.
true.
toString.
, .
valueOf,
. valueOf (
), toString.
EcmaScript, 11.8.5
11.9.3 , 9.1 9.3 .
, , :
{}[0]//?
{}+{}//?
, .
, {...} , , JavaScript
, , ( if, for, ,
, ).
:
//+run
{
alert("")
}
, {}, .
, . :
{}[0]//:[0]
{}+{}//:+{}
, , , {...}
, , .
['x'] == 'x'
: 5
true?
alert(['x']=='x');
: 5
toString valueOf.
alert?
varfoo={
toString:function(){
return'foo';
},
valueOf:function(){
return2;
}
};
alert(foo);
alert(foo+1);
alert(foo+"3");
, .
[] == [] , [ ] == ![ ] ?
: 5
, ?
alert([]==[]);//false
alert([]==![]);//true
,
: 5
, . .
newDate(0)0
newArray(1)[0]+""
({})[0]
[1]+1
[1,2]+[3,4]
[]+null+1
[[0]][0][0]
({}+{})
: 2
sum, :
sum(1)(2)==3;//1+2
sum(1)(2)(3)==6;//1+2+3
sum(5)(1)(2)==6
sum(6)(1)(2)(3)==0
sum(0)(1)(2)(3)(4)(5)==15
.
.
new
{...} .
.
-,
new.
, new.
:
functionAnimal(name){
this.name=name;
this.canWalk=true;
}
varanimal=newAnimal("");
, new.
, , , new,
.
, new:
1. .
2. this .
3. . , this, , .
4. this.
newAnimal(""); :
animal={
name:"",
canWalk:true
}
, newAnimal - (
, ):
functionAnimal(name){
//this={}
//this,
this.name=name;
this.canWalk=true;
//returnthis
}
return
, . , , this,
.
return , :
return , , this.
return , .
, return , ,
, , this.
, :
functionBigAnimal(){
this.name="";
return{name:""};//<
}
alert(newBigAnimal().name);//,this
functionBigAnimal(){
this.name="";
return"";//<
}
alert(newBigAnimal().name);//,this()
new , .
, new :
varanimal=newBigAnimal;//<
//
varanimal=newBigAnimal();
, ,
.
.
, ,
.
.
, newUser(name) name sayHi:
functionUser(name){
this.name=name;
this.sayHi=function(){
alert(":"+this.name);
};
}
varivan=newUser("");
ivan.sayHi();//:
/*
ivan={
name:"",
sayHi:
}
*/
-
, :
functionUser(firstName,lastName){
//
varphrase="";
//
functiongetFullName(){
returnfirstName+""+lastName;
}
this.sayHi=function(){
alert(phrase+","+getFullName());//
};
}
varvasya=newUser("","");
vasya.sayHi();//,
, .
, , this
, vasya.sayHi(), ,
, .
-:
new,
this, .
, this.
, , .
, .
: 2
A B , a,b (.
)?
functionA(){...}
functionB(){...}
vara=newA;
varb=newB;
alert(a==b);//true
Calculator
: 5
- Calculator, :
read() prompt
.
sum() .
mul() .
:
varcalculator=newCalculator();
calculator.read();
alert("="+calculator.sum());
alert("="+calculator.mul());
Accumulator
: 5
- Accumulator(startingValue). , ,
, .
, :
value. value
startingValue.
read() prompt, value.
, value ,
read(), startingValue.
:
varaccumulator=newAccumulator(1);//1
accumulator.read();//prompt
accumulator.read();//prompt
alert(accumulator.value);//
: 5
Calculator, -.
, .
1. : calculate(str) , 1 + 2,
( ),
. + .
:
varcalc=newCalculator;
alert(calc.calculate("3+7"));//10
2. addMethod(name,func),
. name func(a,b),
.
, *, / **:
varpowerCalc=newCalculator;
powerCalc.addMethod("*",function(a,b){
returna*b;
});
powerCalc.addMethod("/",function(a,b){
returna/b;
});
powerCalc.addMethod("**",function(a,b){
returnMath.pow(a,b);
});
varresult=powerCalc.calculate("2**3");
alert(result);//8
.
. .
. .
.
,
,
, , for..in
.
, IE8-. , IE8
, DOM- ( ,
).
Object.defineProperty
, , ,
.
:
Object.defineProperty(obj,prop,descriptor)
:
obj
, .
prop
, .
descriptor
, .
:
value , undefined
writable , true. false.
configurable true, ,
defineProperty. false.
enumerable true, for..in. false.
get , . undefined.
set , . undefined.
, value get/set.
, -, .
writable get/set-.
.
.
:
varuser={};
//1.
user.name="";
//2.
Object.defineProperty(user,"name",{value:""});
-
, , writable configurable:
"usestrict";
varuser={};
Object.defineProperty(user,"name",{
value:"",
writable:false,//"user.name="
configurable:false//"deleteuser.name"
});
//.
//strictmode"user.name="
user.name="";
, usestrict , usestrict
.
, for..in
toString, , for..in.
, .
, toString, , for..in,
:
varuser={
name:"",
toString:function(){returnthis.name;}
};
for(varkeyinuser)alert(key);//name,toString
, toString , .
Object.defineProperty toString ,
enumerable:false. , toString .
varuser={
name:"",
toString:function(){returnthis.name;}
};
//toStringfor..in
Object.defineProperty(user,"toString",{enumerable:false});
for(varkeyinuser)alert(key);//name
, defineProperty ,
toString.
-
, .
get.
, user : firstName surname.
fullName, :
varuser={
firstName:"",
surname:""
}
Object.defineProperty(user,"fullName",{
e
t
:function(){
g
returnthis.firstName+''+this.surname;
}
});
alert(user.fullName);//
, fullName user.fullName.
, .
, ,
set.
, user.fullName :
varuser={
firstName:"",
surname:""
}
Object.defineProperty(user,"fullName",{
get:function(){
returnthis.firstName+''+this.surname;
},
set:function(value){
varsplit=value.split('');
this.firstName=split[0];
this.surname=split[1];
}
});
user.fullName="";
alert(user.firstName);//
alert(user.surname);//
get/set
{...}, -
.
: get set.
, - fullName:
varuser={
firstName:"",
surname:"",
getfullName(){
returnthis.firstName+''+this.surname;
},
setfullName(value){
varsplit=value.split('');
this.firstName=split[0];
this.surname=split[1];
}
};
alert(user.fullName);//()
user.fullName="";
alert(user.firstName);//()
alert(user.surname);//()
get/set!
, get/set ,
? , getFullName, setFullName
, , .
, !
, , User name
age:
functionUser(name,age){
this.name=name;
this.age=age;
}
varpete=newUser("",25);
alert(pete.age);//25
, , .
. , User
age birthday:
functionUser(name,birthday){
this.name=name;
this.birthday=birthday;
}
varpete=newUser("",newDate(1987,6,1));
, age?
, , , , , ,
,
.
get- age :
functionUser(name,birthday){
this.name=name;
this.birthday=birthday;
//agebirthday
Object.defineProperty(this,"age",{
get:function(){
vartodayYear=newDate().getFullYear();
returntodayYearthis.birthday.getFullYear();
}
});
}
varpete=newUser("",newDate(1987,6,1));
alert(pete.birthday);//
alert(pete.age);//
, pete.age , . ,
pete.age() .
, defineProperty , ,
, ,
.
Object.defineProperties(obj, descriptors)
:
varuser={}
Object.defineProperties(user,{
firstName:{
value:""
},
surname:{
value:""
},
fullName:{
get:function(){
returnthis.firstName+''+this.surname;
}
}
});
alert(user.fullName);//
Object.keys(obj)
Object.getOwnPropertyNames(obj)
.
Object.keys enumerable-.
Object.getOwnPropertyNames :
varobj={
a:1,
b:2,
internal:3
};
Object.defineProperty(obj,"internal",{
enumerable:false
});
alert(Object.keys(obj));//a,b
alert(Object.getOwnPropertyNames(obj));//a,internal,b
Object.getOwnPropertyDescriptor(obj, prop)
obj[prop].
defineProperty
, :
varobj={
test:5
};
vardescriptor=Object.getOwnPropertyDescriptor(obj,'test');
//value,...
deletedescriptor.value;//..value/writable
deletedescriptor.writable;
descriptor.get=function(){//get
alert("Preved:)");
};
//
//defineProperty
deleteobj.test;
Object.defineProperty(obj,'test',descriptor);
obj.test;//Preved:)
, :
Object.preventExtensions(obj)
.
Object.seal(obj)
, configurable:false.
Object.freeze(obj)
, , configurable:
false,writable:false.
Object.isExtensible(obj)
Object.isSealed(obj)
Object.isFrozen(obj)
true, Object.preventExtensions/seal/freeze.
get/set-
: 5
User, this.fullName:
functionUser(fullName){
this.fullName=fullName;
}
varvasya=newUser("");
, firstName lastName, ,
, :
varvasya=newUser("");
//firstName/lastName
alert(vasya.firstName);//
alert(vasya.lastName);//
//lastName
vasya.lastName='';
alert(vasya.fullName);//
: fullName , firstName/lastName
get/set. .
, ,
. -.
Article.count Article.DEFAULT_FORMAT:
functionArticle(){
Article.count++;
}
Article.count=0;//
Article.DEFAULT_FORMAT="html";//
, , .
, , Article.DEFAULT_FORMAT.
: String.fromCharCode,
Date.parse.
Article Article.showCount():
functionArticle(){
Article.count++;
//...
}
Article.count=0;
Article.showCount=function(){
alert(this.count);//(1)
}
//
newArticle();
newArticle();
Article.showCount();//(2)
Article.count , Article.showCount .
this . ,
, . (1) Article.
:
.
, Journal . ,
, .
, .
, , ,
.
Journal.compare:
functionJournal(date){
this.date=date;
//...
}
//,0,AB,0
Journal.compare=function(journalA,journalB){
returnjournalA.datejournalB.date;
};
functionJournal(date){
this.date=date;
this.formatDate=function(date){
returndate.getDate()+'.'+(date.getMonth()+1)+'.'+date.getFullYear();
};
this.getTitle=function(){
return""+this.formatDate(this.date);
};
}
Journal.compare=function(journalA,journalB){
returnjournalA.datejournalB.date;
};
//:
varjournals=[
newJournal(newDate(2012,1,1)),
newJournal(newDate(2012,0,1)),
newJournal(newDate(2011,11,1))
];
functionfindMin(journals){
varmin=0;
for(vari=0;i<journals.length;i++){
//
if(Journal.compare(journals[min],journals[i])>0)min=i;
}
returnjournals[min];
}
alert(findMin(journals).getTitle());
,
.
, formatDate(date) .
, ,
.
:
functionJournal(){/*...*/}
Journal.formatDate=function(date){
returndate.getDate()+'.'+(date.getMonth()+1)+'.'+date.getFullYear();
}
//Journal,
l
e
r
t
(
J
o
u
r
n
a
l
.
f
o
r
m
a
t
D
a
t
e
(
n
e
w
D
a
t
e
)
);
a
, . ,
Date. - :
newDate() ,
newDate(milliseconds) milliseconds,
newDate(year,month,day...) , ,
newDate(datestring) datestring
.
, (
).
String.fromCharCode(code).
:
varstr=String.fromCharCode(65);
alert(str);//'A'
, - .
, User: newUser() newUser({name:
'',age:25}).
, , - User:
functionUser(userData){
if(userData){//if
this.name=userData.name;
this.age=userData.age;
}else{//
this.name='';
}
this.sayHi=function(){
alert(this.name)
};
//...
}
//
varguest=newUser();
guest.sayHi();//
varknownUser=newUser({
name:'',
age:25
});
knownUser.sayHi();//
.
: User.createAnonymous User.createFromData.
:
functionUser(){
this.sayHi=function(){
alert(this.name)
};
}
User.createAnonymous=function(){
varuser=newUser;
user.name='';
returnuser;
}
User.createFromData=function(userData){
varuser=newUser;
user.name=userData.name;
user.age=userData.age;
returnuser;
}
//
varguest=User.createAnonymous();
guest.sayHi();//
varknownUser=User.createFromData({
name:'',
age:25
});
knownUser.sayHi();//
.
, , .
, .. createFromData ,
, .
. , ,
. : User.createAdmin=function(){...}.
,
.
,
, .. , ,
.
.
:
, .
.
, , .
, , .
.
: 5
Article:
.
.
.
Article.showStats() .
:
functionArticle(){
this.created=newDate();
//......
}
newArticle();
newArticle();
Article.showStats();//:2,:()
newArticle();
Article.showStats();//:3,:()
call
call:
func.call(context,arg1,arg2,...)
functionshowFullName(){
alert(this.firstName+""+this.lastName);
}
, , JavaScript this.
this,
.
showFullName.call(user) , this=user, :
functionshowFullName(){
alert(this.firstName+""+this.lastName);
}
varuser={
firstName:"",
lastName:""
};
//this=user
showFullName.call(user)//""
call .
showFullName, :
varuser={
firstName:"",
surname:"",
patronym:""
};
functionshowFullName(firstPart,lastPart){
alert(this[firstPart]+""+this[lastPart]);
}
//f.call(,1,2,...)
showFullName.call(user,'firstName','surname')//""
showFullName.call(user,'firstName','patronym')//""
call , ,
.
( . method borrowing).
arguments.
, arguments , , push,
pop, join . ,
! join :
functionprintArgs(){
arguments.join=[].join;//(1)
varargStr=arguments.join(':');//(2)
alert(argStr);//1:2:3
}
printArgs(1,2,3);
1. (1) [] [].join. ,
, . , ,
, [].join .
2. (2) join arguments, .
?
join arguments.
- , arguments ? , , ?
.
:
join
functionjoin(separator){
if(!this.length)return'';
varstr=this[0];
for(vari=1;i<this.length;i++){
str+=separator+this[i];
}
returnstr;
}
, this, length. ,
. .
this :
varobj={//length
0:"",
1:"",
2:"",
length:3
};
obj.join=[].join;
alert(obj.join(';'));//"A;;"
, !
, arguments .
, length [].join. ,
arguments, (!) , join.
[].join, , : join
, .
call:
functionprintArgs(){
varjoin=[].join;//
//jointhis=arguments,
//arguments.join(':')
varargStr=join.call(arguments,':');
alert(argStr);//1:2:3
}
printArgs(1,2,3);
. , .
: [].slice.call(arguments)
JavaScript arguments .
: slice .
arr.slice(start,end)
arr start end. start end , .
arguments:
functionprintArgs(){
//arr.slice()this
varargs=[].slice.call(arguments);
alert(args.join(','));//args
}
printArgs('','','');//,,
join, , slice
length. arguments.
apply
, ,
: apply.
func.apply func.call,
.
func.call(context,arg1,arg2);
//
func.apply(context,[arg1,arg2]);
, c :
showFullName.call(user,'firstName','surname');
showFullName.apply(user,['firstName','surname']);
apply call ,
.
, JavaScript Math.max(a,b,c...),
:
alert(Math.max(1,5,2));//5
apply , :
vararr=[];
arr.push(1);
arr.push(5);
arr.push(2);
//arr
alert(Math.max.apply(null,arr));//5
apply ,
, ? this null.
, Math.max(1,2,3)
Math.max.apply(Math,[1,2,3]). Math.
,
Math.max this. , this,
? , apply
!
usestrict:
functionf(){
alert(this);//window
}
f.call(null);
this
this , :
obj.func(...)//this=obj
obj["func"](...)
func(...)//this=window(ES3)/undefined(ES5)
new
newfunc()//this={}()
func.apply(context,args)//this=context()
func.call(context,arg1,arg2,...)
: 5
sum, :
functionsum(arr){
returnarr.reduce(function(a,b){
returna+b;
});
}
alert(sum([1,2,3]));//6(=1+2+3)
sumArgs(), :
functionsumArgs(){
/**/
}
alert(sumArgs(1,2,3));//6,,
: 5
applyAll(func,arg1,arg2...), func
.
func(arg1,arg2...), func ,
, .
:
//Math.max2,2,3
alert(applyAll(Math.max,2,2,3));//3
//Math.min2,2,3
alert(applyAll(Math.min,2,2,3));//2
applyAll, , , :
functionsum(){//:sum(1,2,3)=6
return[].reduce.call(arguments,function(a,b){
returna+b;
});
}
functionmul(){//:mul(2,3,4)=24
return[].reduce.call(arguments,function(a,b){
returna*b;
});
}
alert(applyAll(sum,1,2,3));//>sum(1,2,3)=6
alert(applyAll(mul,2,3,4));//>mul(2,3,4)=24
: bind
JavaScript this, ,
, .
.
, this=undefined.
, .
, , .
setTimeout(func,ms),
func ms (=1/1000 ).
, setTimeout setInterval,
.
1000, 1 :
setTimeout(function(){
alert("");
},1000);
,
1 :
varuser={
firstName:"",
sayHi:function(){
alert(this.firstName);
}
};
setTimeout(user.sayHi,1000);//undefined(!)
"", undefined!
, setTimeout user.sayHi,
. , :
varf=user.sayHi;
setTimeout(f,1000);//user
- ,
. , ,
?
, , ,
.
1:
:
varuser={
firstName:"",
sayHi:function(){
alert(this.firstName);
}
};
setTimeout(function(){
user.sayHi();//
},1000);
, user .
:
varuser={
firstName:"",
sayHi:function(who){
alert(this.firstName+":,"+who);
}
};
setTimeout(function(){
user.sayHi("");//:,
},1000);
!
, setTimeout( ) user
? , user=(
) !
.
2: bind
bind(func,context),
func:
functionbind(func,context){
returnfunction(){//(*)
returnfunc.apply(context,arguments);
};
}
, , , :
functionf(){
alert(this);
}
varg=bind(f,"Context");
g();//Context
, f "Context", :
function(){//(*)
returnf.apply("Context",arguments);
};
g.
, g, f, f.apply("Context",arguments)
"Context", .
g , :
functionf(a,b){
alert(this);
alert(a+b);
}
varg=bind(f,"Context");
g(1,2);//Context,3
, g(...), f .apply.
, bind(func,context) , func, ,
context.
user.sayHi. bind:
functionbind(func,context){
returnfunction(){
returnfunc.apply(context,arguments);
};
}
varuser={
firstName:"",
sayHi:function(){
alert(this.firstName);
}
};
setTimeout(bind(user.sayHi,user),1000);
!
bind(user.sayHi,user) -,
user.sayHi user. 1000.
user.sayHi ,
.
varuser={
firstName:"",
sayHi:function(who){//sayHi
alert(this.firstName+":,"+who);
}
};
varsayHi=bind(user.sayHi,user);
//,""
sayHi("");//:,
sayHi("");//:,
bind
, ,
sayHi.
bind , ,
.
3: bind
JavaScript ( es5-shim
bind , .
IE8-)
, bind, .
:
functionf(a,b){
alert(this);
alert(a+b);
}
//
//varg=bind(f,"Context");
varg=f.bind("Context");
g(1,2);//Context,3
bind:
varwrapper=func.bind(context[,arg1,arg2...])
func
context
, func
arg1, arg2,
arg1,arg2...
, , .
func.bind(context) bind(func,context),
. , wrapper , func.
, , .
bind:
varuser={
firstName:"",
sayHi:function(){
alert(this.firstName);
}
};
//setTimeout(bind(user.sayHi,user),1000);
setTimeout(user.sayHi.bind(user),1000);//
, JavaScript.
bind.
bind call/apply
bind call/apply , .
call/apply .
bind . ,
, , .
: bindAll
,
:
for(varpropinuser){
if(typeofuser[prop]=='function'){
user[prop]=user[prop].bind(user);
}
}
JS- ,
_.bindAll(obj) .
. .
, . , .
(currying) ,
.
, func.bind(context,...) ,
, .
, mul(a,b):
functionmul(a,b){
returna*b;
};
bind double, .
mul :
//double
vardouble=mul.bind(null,2);//null,
alert(double(3));//=mul(2,3)=6
alert(double(4));//=mul(2,4)=8
alert(double(5));//=mul(2,5)=10
double mul ,
bind, 2.
, double (partial function) mul.
triple :
vartriple=mul.bind(null,3);//null,
alert(triple(3));//=mul(3,3)=9
alert(triple(4));//=mul(3,4)=12
alert(triple(5));//=mul(3,5)=15
bind
setTimeout - .
, , -,
(double, triple), -,
, bind.
ask
, ask:
functionask(question,answer,ok,fail){
varresult=prompt(question,'');
if(result.toLowerCase()==answer.toLowerCase())ok();
elsefail();
}
question, answer,
ok(), fail().
,
. , , alert/prompt JavaScript-
, , .
:
ask("?","",fly,die);
functionfly(){
alert(':)');
}
functiondie(){
alert(':(');
}
.
obj.func(),
-, :
setTimeout(function(){
obj.func();
})
bind:
setTimeout(obj.func.bind(obj));
bind ,
.
bind ( ),
.
- bind
: 3
bind IE8-
:
functionbind(func,context/*,args*/){
varbindArgs=[].slice.call(arguments,2);//(1)
functionwrapper(){//(2)
varargs=[].slice.call(arguments);
varunshiftArgs=bindArgs.concat(args);//(3)
returnfunc.apply(context,unshiftArgs);//(4)
}
returnwrapper;
}
mul.bind(null,2) bind(mul,null,2).
, , ,
.
bind
: 5
?
functionf(){
alert(this);
}
varuser={
g:f.bind("Hello")
}
user.g();
bind
: 5
?
functionf(){
alert(this.name);
}
f=f.bind({name:""}).bind({name:""});
f();
bind
: 5
. bind?
.
functionsayHi(){
alert(this.name);
}
sayHi.test=5;
alert(sayHi.test);//5
varbound=sayHi.bind({
name:""
});
alert(bound.test);//??
: 5
user.checkPassword() , ask,
loginOk/loginFail .
, . ?
, ( ).
"usestrict";
functionask(question,answer,ok,fail){
varresult=prompt(question,'');
if(result.toLowerCase()==answer.toLowerCase())ok();
elsefail();
}
varuser={
login:'',
password:'12345',
loginOk:function(){
alert(this.login+'');
},
loginFail:function(){
alert(this.login+':');
},
checkPassword:function(){
ask("?",this.password,this.loginOk,this.loginFail);
}
};
user.checkPassword();
P.S. , user ,
user.checkPassword() :
varvasya=user;
user=null;
vasya.checkPassword();
: 5
. user
.
user.loginOk() user.loginFail() :
user.loginDone(true/false), true fail
.
, .
: user
, , ( ).
?
, .
"usestrict";
functionask(question,answer,ok,fail){
varresult=prompt(question,'');
if(result.toLowerCase()==answer.toLowerCase())ok();
elsefail();
}
varuser={
login:'',
password:'12345',
//ask
loginDone:function(result){
alert(this.login+(result?'':''));
},
checkPassword:function(){
ask("?",this.password,
function(){
user.loginDone(true);
},
function(){
user.loginDone(false);
}
);
}
};
varvasya=user;
user=null;
vasya.checkPassword();
.
, , bind, .
?
-,
JavaScript :
, ,
, . ,
, - , , .
,
/ .
, -
.
bind
bind:
functionbind(func,context){
returnfunction(){
returnfunc.apply(context,arguments);
};
}
bind(func,context) , this
func.
-
, .
timingDecorator ,
-,
timer -.
:
functionf(x){}//
vartimers={};//
//
f=timingDecorator(f,"myFunc");
//
f(1);
f(2);
f(3);//,
alert(timers.myFunc);//f
timingDecorator
.
:
vartimers={};
//ftimers[timer]
functiontimingDecorator(f,timer){
returnfunction(){
varstart=performance.now();
varresult=f.apply(this,arguments);//(*)
if(!timers[timer])timers[timer]=0;
timers[timer]+=performance.now()start;
returnresult;
}
}
//,:
functionfibonacci(n){
return(n>2)?fibonacci(n1)+fibonacci(n2):1;
}
//:fibonacci
fibonacci=timingDecorator(fibonacci,"fibo");
//...
alert(fibonacci(10));//55
alert(fibonacci(20));//6765
//...
//
alert(timers.fibo+'');
(*) , :
varresult=f.apply(this,arguments);//(*)
( . forwarding):
apply f, f ,
, .
JavaScript, , . ,
, , .
:
functionsum(a,b){
returna+b;
}
//
alert(sum(true,{name:"",age:35}));//true[Objectobject]
- , sum ,
, . - sum
, .
,
. , .
JavaScript ,
- , - ,
.
, ,
.
, , ,
:
//
functioncheckNumber(value){
returntypeofvalue=='number';
}
//,f
//checks
functiontypeCheck(f,checks){
returnfunction(){
for(vari=0;i<arguments.length;i++){
if(!checks[i](arguments[i])){
alert(""+i);
return;
}
}
returnf.apply(this,arguments);
}
}
functionsum(a,b){
returna+b;
}
//
sum=typeCheck(sum,[checkNumber,checkNumber]);//
//
alert(sum(1,2));//3,
//
sum(true,null);//0
sum(1,["array","in","sum?!?"]);//1
, , , ,
, ?
,
.
, .
, isAdmin(), true,
.
checkPermissionDecorator,
:
, checkPermissionDecorator(f). ,
f , :
functioncheckPermissionDecorator(f){
returnfunction(){
if(isAdmin()){
returnf.apply(this,arguments);
}
alert('');
}
}
:
functionsave(){...}
save=checkPermissionDecorator(save);
//save()
, .
- .
, !
.
, .
, .
, , ,
, ,
, (!) .
, ,
. .
(1 )
: 5
makeLogging(f,log), f log.
f, ()
log, f.
, f .
:
functionwork(a){
/*...*///work,
}
functionmakeLogging(f,log){/**/}
varlog=[];
work=makeLogging(work,log);
work(1);//1,log
work(5);//5,log
for(vari=0;i<log.length;i++){
alert(':'+log[i]);//":1",":5"
}
( )
: 3
makeLogging(func,log), func ,
log.
(1 ), func
.
:
functionwork(a,b){
alert(a+b);//work
}
functionmakeLogging(f,log){/**/}
varlog=[];
work=makeLogging(work,log);
work(1,2);//3
work(4,5);//9
for(vari=0;i<log.length;i++){
varargs=log[i];//i
alert(':'+args.join());//":1,2",":4,5"
}
: 5
makeCaching(f), f ,
.
f , .
1. f
.
2.
.
:
functionf(x){
returnMath.random()*x;//random
}
functionmakeCaching(f){/**/}
f=makeCaching(f);
vara,b;
a=f(1);
b=f(1);
alert(a==b);//true()
b=f(2);
alert(a==b);//false,=>
JavaScript, ,
.
: [[Class]], instanceof
,
, - , . ,
- .
typeof
typeof.
typeof , null, .
:
alert(typeof1);//'number'
alert(typeoftrue);//'boolean'
alert(typeof"");//'string'
alert(typeofundefined);//'undefined'
alert(typeofnull);//'object'()
alert(typeofalert);//'function'
, typeof ,
'object':
alert(typeof{});//'object'
alert(typeof[]);//'object'
alert(typeofnewDate);//'object'
typeof, .
[[Class]]
,
toString.
[[Class]],
.
, . ,
, toString
Object.
[[Class]] , "[object
]".
:
vartoString={}.toString;
vararr=[1,2];
alert(toString.call(arr));//[objectArray]
vardate=newDate;
alert(toString.call(date));//[objectDate]
varuser={name:""};
alert(toString.call(user));//[objectObject]
toString, {}.
, Date Array toString,
.
toString obj,
, , [[Class]].
[[Class]] toString
Object, .
, JavaScript - ,
call/apply.
{}.toString.
:
alert({}.toString.call(123));//[objectNumber]
alert({}.toString.call(""));//[objectString]
{}.toString
,
{}.toString.call(...) . , alert(
{}.toString...) .
, {}
. {}.toString.call(...):
{}//
.toString.call(...)//?,!
, .
, ({}.toString...) .
getClass,
[[Class]]:
functiongetClass(obj){
return{}.toString.call(obj).slice(8,1);
}
alert(getClass(newDate));//Date
alert(getClass([1,2,3]));//Array
, [[Class]]
. , . , ,
"Object".
:
functionUser(){}
varuser=newUser();
alert({}.toString.call(user));//[objectObject],[objectUser]
Array.isArray()
: Array.isArray(arr). true
arr :
alert(Array.isArray([1,2,3]));//true
alert(Array.isArray("notarray"));//false
.
, Object.isObject, Date.isDate .
instanceof
instanceof , ,
, .
functionUser(){}
varuser=newUser();
alert(userinstanceofUser);//true
,
: If it looks like a duck, swims like a duck and quacks like a duck, then it probably is a duck (who
cares what it really is)".
: , , , ,
( , )".
.
, , , Array.isArray,
, splice:
varsomething=[1,2,3];
if(something.splice){
alert('!,!');
}
if something.splice(),
something.splice. , ..
true.
, getTime:
varx=newDate();
if(x.getTime){
alert('!');
alert(x.getTime());//
}
, , .
: ,
, ( , ).
, ,
, .
, duck typing
. , .
- .
sayHi(who),
, :
functionsayHi(who){
if(Array.isArray(who)){
who.forEach(sayHi);
}else{
alert(','+who);
}
}
//
sayHi("");//,
//
sayHi(["",""]);//,...
//!
sayHi(["","",["",""]]);//......
forEach:
functionsayHi(who){
if(who.forEach){//forEach
who.forEach(sayHi);//,""
}else{
alert(','+who);
}
}
( !) .
typeof.
:
1. null, .
2. function, ,
.
[[Class]],
{}.toString.call(obj).slice(8,1). ,
.
objinstanceofFunc, obj Func,
. : instanceof.
, , ,
. .
formatDate
: 5
formatDate(date), dd.mm.yy.
:
1. Date.
2. , yyyymmdd .
3. 01.01.1970.
4. [,,],
, ,
.
:
functionformatDate(date){/**/}
alert(formatDate('20111002'));//02.10.11
alert(formatDate(1234567890));//14.02.09
alert(formatDate([2014,0,1]));//01.01.14
alert(formatDate(newDate(2014,0,1)));//01.01.14
JSON, toJSON
JSON
.
JavaScript.
,
, .
,
JSON .
JSON
JSON (RFC 4627
JavaScript- {...}
[...]
:
,
,
true/false,
null.
JSON.
JSON JavaScript :
JSON.parse JSON.
JSON.stringify JSON, ,
JavaScript .
JSON.parse
JSON.parse(str) JSON JavaScript-//
.
:
varnumbers="[0,1,2,3]";
numbers=JSON.parse(numbers);
alert(numbers[1]);//1
:
varuser='{"name":"","age":35,"isAdmin":false,"friends":[0,1,2,3]}';
user=JSON.parse(user);
alert(user.friends[1]);//1
,
. .
JSON- JavaScript-
JSON JavaScript-,
.
, :
{
a
m
e
:"",//:name!
n
"
s
u
r
n
a
m
e
"
:
'
',//:''!
"age":35//...
"isAdmin":false//
}
, JSON .
.
JSON, JSON5
, ., JavaScript. ,
.
: JSON.parse(str, reviver)
JSON.parse .
, event.
:
//title:,date:
varstr='{"title":"","date":"20121130T12:00:00.000Z"}';
, JavaScript-.
JSON.parse:
varstr='{"title":"","date":"20141130T12:00:00.000Z"}';
varevent=JSON.parse(str);
alert(event.date.getDate());//!
, !
, event.date , Date.
JSON.parse, ?
JSON.parse(str,reviver)
reviver, function(key,value).
, JSON.parse
- ,
undefined, .
, date :
//UTC
varstr='{"title":"","date":"20141130T12:00:00.000Z"}';
varevent=JSON.parse(str,function(key,value){
if(key=='date')returnnewDate(value);
returnvalue;
});
alert(event.date.getDate());//!
, :
varschedule='{\
"events":[\
{"title":"","date":"20141130T12:00:00.000Z"},\
{"title":"","date":"20150418T12:00:00.000Z"}\
]\
}';
schedule=JSON.parse(schedule,function(key,value){
if(key=='date')returnnewDate(value);
returnvalue;
});
alert(schedule.events[1].date.getDate());//!
, JSON.stringify
JSON.stringify(value,replacer,space) () JSON.
:
varevent={
title:"",
date:""
};
varstr=JSON.stringify(event);
alert(str);//{"title":"","date":""}
//.
event=JSON.parse(str);
toJSON.
, .
:
varroom={
number:23,
occupy:function(){
alert(this.number);
}
};
event={
title:"",
date:newDate(Date.UTC(2014,0,1)),
room:room
};
alert(JSON.stringify(event));
/*
{
"title":"",
"date":"20140101T00:00:00.000Z",//(1)
"room":{"number":23}//(2)
}
*/
:
1. . : toJSON.
UTC.
2. room toJSON. .
, , , :
varroom={
number:23,
toJSON:function(){
returnthis.number;
}
};
alert(JSON.stringify(room));//23
JSON , DOM.
:
varuser={
name:"",
age:25,
window:window
};
alert(JSON.stringify(user));//!
//TypeError:ConvertingcircularstructuretoJSON(Chrome)
! , ?
. window
, .
?
JSON.stringify(value,replacer) ,
.
:
varuser={
name:"",
age:25,
window:window
};
alert(JSON.stringify(user,["name","age"]));
//{"name":"","age":25}
function(key,
value), value undefined,
:
varuser={
name:"",
age:25,
window:window
};
varstr=JSON.stringify(user,function(key,value){
if(key=='window')returnundefined;
returnvalue;
});
alert(str);//{"name":"","age":25}
window.
, . - .
replacer
, , ..,
replacer.
JSON.stringify(value,replacer,space) space.
JSON
, .
:
varuser={
name:"",
age:25,
roles:{
isAdmin:false,
isEditor:true
}
};
varstr=JSON.stringify(user,"",4);
alert(str);
/*:
{
"name":"",
"age":25,
"roles":{
"isAdmin":false,
"isEditor":true
}
}
*/
JSON ( ) .
JSON.parse
.
JSON.stringify
JSON
: 3
leader JSON:
varleader={
name:"",
age:35
};
JSON
: 3
team JSON:
varleader={
name:""
};
varsoldier={
name:""
};
//!
leader.soldier=soldier;
soldier.leader=leader;
varteam=[leader,soldier];
1. JSON.stringify(team)? , ?
2. ?
setTimeout setInterval
JavaScript -,
.
, Node.JS.
setTimeout
:
vartimerId=setTimeout(func/code,delay[,arg1,arg2...])
:
func/code
. ,
.
delay
, 1000 1 .
arg1, arg2
, . IE9-.
, delay.
, func() :
functionfunc(){
alert('');
}
setTimeout(func,1000);
( IE9-):
functionfunc(phrase,who){
alert(phrase+','+who);
}
setTimeout(func,1000,"","");//,
,
.
:
setTimeout("alert('')",1000);
, ,
, , ,
.
, :
setTimeout(function(){alert('')},1000);
clearTimeout
setTimeout timerId,
.
:
vartimerId=setTimeout(...);
clearTimeout(timerId);
, ().
.
vartimerId=setTimeout(function(){alert(1)},1000);
alert(timerId);//
clearTimeout(timerId);
alert(timerId);//,
alert, .
JavaScript-, Node.JS, ,
.
,
JavaScript .
JavaScript, Timers
Node.JS .
HTML5
setInterval
setInterval , setTimeout.
vartimerId=setInterval(func/code,delay[,arg1,arg2...])
. , setTimeout,
, .
clearInterval(timerId).
,
5 :
//2
vartimerId=setInterval(function(){
alert("");
},2000);
//5
setTimeout(function(){
clearInterval(timerId);
alert('');
},5000);
Chrome/Opera/Safari
, OK alert? .
Chrome, Opera Safari
alert/confirm/prompt. IE Firefox .
, alert , Firefox/IE alert
( ), Chrome/Opera/Safari 2
.
setTimeout
setInterval setTimeout:
/**:
vartimerId=setInterval(function(){
alert("");
},2000);
*/
vartimerId=setTimeout(functiontick(){
alert("");
timerId=setTimeout(tick,2000);
},2000);
.
setTimeout , setInterval,
-,
.
, , 5 .
, , 10, 20, 60
, .
, ,
, .
setTimeout , setInterval .
. setInterval:
vari=1;
setInterval(function(){
func(i);
},100);
setTimeout:
vari=1;
setTimeout(functionrun(){
func(i);
setTimeout(run,100);
},100);
?
func setInterval, !
, ,
.
func , ,
100.
, , ,
setInterval ( ),
.
, setInterval,
.
IE, JavaScript.
setTimeout:
setTimeout 100.
, .
JavaScript , ,
.
setInterval/setTimeout ,
, ,
.
//,()
setTimeout(function(){},100);
setTimeout .
setInterval .
, ,
setInterval .
.
4 . 15.
, 4.
setTimeout(..,1) setTimeout(..,4).
.
setInterval
0 () 20 ().
. ,
. ,
.
0
2
4
6
8
10
12
14
16
18
20
:
Internet Explorer, setInterval(..,0) .
setInterval, .. setTimeout(..,0) .
4?
4, 1? ?
. Chrome -
, , ,
setTimeout(..,0), . ,
, 100% , .
, , .
, .
4.
, .
setInterval(...,4) 4, 30 1000.
( )
setTimeout/setInterval, .
(Chrome, FF, IE10) , 1
. , , .
, ,
. IE.
, .
JavaScript
. setInterval .
: 4 , .
,
.
, ,
, , .
, , ,
- , .
, 100 , 20
100 . CPU :
100 , , 200 ,
50.
.
100
: 5
printNumbersInterval(),
1 20, 100. ,
2000, 100 .
, , :
printNumbersInterval()
P.S. setInterval.
100, setTimeout
: 5
, 100,
setTimeout setInterval.
setInterval setTimeout?
: 5
: JavaScript,
- . ,
, .
, ,
: 20 10.
, :
1. setInterval, :
timer=setInterval(function(){
if()highlight();
elseclearInterval(timer);
},10);
2. setTimeout:
setTimeout(functiongo(){
highlight();
if()setTimeout(go,10);
},10);
? ?
setTimeout?
: 5
setTimeout, hardWork,
, .
setTimeout? :
1. hardWork.
2. hardWork.
3. hardWork.
4. 100 hardWork.
alert ?
setTimeout(function(){
alert(i);
},100);
vari;
functionhardWork(){
//>100,
for(i=0;i<1e8;i++)hardWork[i%2]=i;
}
hardWork();
setInterval?
: 5
setInterval 10, 50 .
f, ( )
100.
setInterval, ?
:
1. , , f.
2. , , f.
3. , , f.
4. , .
5. -, .
alert (*)?
vari;
vartimer=setInterval(function(){//setInterval10
i++;
},10);
setTimeout(function(){//50setInterval
clearInterval(timer);
alert(i);//(*)
},50);
//
functionf(){
//
//100
for(i=0;i<1e8;i++)f[i%2]=i;
}
f();
?
: 5
:
varrunner1=newRunner();
varrunner2=newRunner();
step(), , steps.
step() ,
, .
setInterval, setTimeout
5 ?
//?
setInterval(function(){
runner1.step();
},15);
//?
setTimeout(functiongo(){
runner2.step();
setTimeout(go,15);
},15);
setTimeout(function(){
alert(runner1.steps);
alert(runner2.steps);
},5000);
-
: 5
delay(f,ms), f,
ms.
:
functionf(x){
alert(x);
}
varf1000=delay(f,1000);
varf1500=delay(f,1500);
f1000("");//""1000
f1500("2");//"2"1500
, delay ms f.
, delay :
this.
.
N
: 5
debounce(f,ms), , f
, ms.
. .
:
functionf(){...}
varf=debounce(f,1000);
f(1);//
f(2);//
setTimeout(function(){f(3)},100);//(100)
setTimeout(function(){f(4)},1100);//
setTimeout(function(){f(5)},1500);//
, debounce f,
ms.
.
: 5
throttle(f,ms) , ,
f , ms.
debounce:
, ..
.
, , throttle
, .
, .
JavaScript , . , ,
, 100 ( 10).
.
, . 100, .
, ,
onmousemove.
throttle(onmousemove,100), , ,
onmousemove. , ,
onmousemove, 100.
,
- . ,
!
:
1. ( ,
).
2. (-) ,
100 .
3. 100 , .
- .
4. - ,
100 .
, ,
. , .
:
varf=function(a){
console.log(a)
};
//1000
varf1000=throttle(f,1000);
f1000(1);//1
f1000(2);//(,1000)
f1000(3);//(,1000)
//1000...
//3,2
: eval
eval(code) , .
.
eval
eval , :
vara=1;
(function(){
vara=2;
eval('alert(a)');//2
})()
, .
eval :
:
alert(eval('1+1'));//2
eval .
, :
varx=5;
eval("alert(x);x=10");//5,
alert(x);//10,eval
eval
eval- .
usestrict eval-
, , eval,
.
"usestrict";
eval("vara=5;functionf(){}");
alert(a);//,
//f
, eval ,
, ,
.
eval
, eval . .
eval is evil (eval ).
: - JavaScript , ,
eval . .
, .
, eval
, .
, eval.
, :
functionsayHi(){
varphrase="";
eval(str);
}
:
functionsayHi(){
vara="";
alert(a);
}
a :
functionsayHi(){
alert("");
}
, - eval,
.
, eval
,
.
, .
,
. , , ,
.
eval . :
1. , IE8-, eval , window.eval.
:
vara=1;
(function(){
vara=2;
window.eval('alert(a)');//1,,IE8
})();
new Function
, , , , , eval,
- .
, :
JavaScript.
, .
, eval,
c : newFunction.
newFunction('a,b','....') a,b
. , ,
.
:
vara=2,
b=3;
//a,beval
//
varmul=newFunction('a,b','returna*b;');
alert(mul(a,b));//6
JSON eval
IE7- JSON.stringify JSON.parse, JSON
eval.
JSON , - ,
.
eval(code) , , ,
JSON.
:
varstr='{\
"name":"",\
"age":25\
}';
varuser=eval('('+str+')');
alert(user.name);//
eval('('+str+')'), eval(str)?
, JavaScript { ,
.
. , , .
eval , ,
, -
, , eval , :
varuser=eval('{"name":"","age":25}');
eval (...), ,
, :
varuser=eval('({"name":"","age":25})');
alert(user.age);//25
, JSON!
JSON , ,
eval .
, ( - ,
) JSON JavaScript-.
, , JSON.parse.
JSON.parse JSON ,
eval , - ,
- ..
eval(str) .
JavaScript .
eval . ,
.
window.eval/execScript. ,
, , .
newFunction.
, .
eval , JSON, toJSON.
Eval-
: 4
, (prompt)
.
, try..catch
, . , ,
().
, , , .
, - ,
, - .
JavaScript try..catch.
try..catch
try..catch : try, catch:
try{
//...
}catch(err){
//
}
:
1. try.
2. , catch(err),
try catch.
3. , try ,
catch(err).
err( )
.
, try ,
catch.
.
: alert(1) (2):
try{
l
e
r
t
(
'
t
r
y
'
)
;
/
/
(
1
)
<
a
//..
l
e
r
t
(
'
t
r
y
'
)
;
/
/
(
2
)
<
a
}catch(e){
alert('catch,');//(3)
}
alert("...");
: (1) (3):
try{
a
l
e
r
t
(
'
t
r
y
'
)
;
/
/
(
1
)
<
lalala;//,!
alert('try');//(2)
}catch(e){
l
e
r
t
(
'
'
+
e
.
n
a
m
e
+
"
:
"
+
e
.
m
e
s
s
a
g
e
+
"
\
n
"
+
e
.
s
t
a
c
k
)
;
/
/
(
3
)
<
a
}
alert("...");
try..catch,
, -
, try..catch .
, .
,
, .
try..catch
, , , ,
setTimeout, try..catch :
try{
setTimeout(function(){
thrownewError();//
},1000);
}catch(e){
alert("");
}
, setTimeout, ,
try..catch.
setTimeout, try..catch
.
. :
name
. , : "ReferenceError".
message
.
stack
, IE8-, stack,
, .
, , . Error MDN
Error MSDN .
JavaScript JSON.parse(str)
JavaScript- ( ) .
, , ,
.
JSON.parse, :
vardata='{"name":"","age":30}';//,
varuser=JSON.parse(data);//
//userJS
alert(user.name);//
alert(user.age);//30
vardata="HasError";//
try{
varuser=JSON.parse(data);//<
alert(user.name);//
}catch(e){
//...catch
alert(",,");
alert(e.name);
alert(e.message);
}
alert , :
, ,
.
, JSON
name:
vardata='{"age":30}';//
try{
varuser=JSON.parse(data);//<
alert(user.name);//undefined
}catch(e){
//
alert(",");
}
JSON.parse , . , name
, "HasError".
,
, throw.
throw
throw .
: throw<>.
, ,
, , , ,
, name message.
: new
Error(message) .
JavaScript : SyntaxError, ReferenceError,
RangeError . ,
.
newSyntaxError(message).
, JSON.parse.
vardata='{"age":30}';//
try{
varuser=JSON.parse(data);//<
if(!user.name){
thrownewSyntaxError("");
}
alert(user.name);
}catch(e){
alert(",");
}
, catch :
JSON.parse .
,
. , - ?
, ! ,
, 10 , 11
. , .
catch ,
. - ,
.
, catch , .
: catch(e) ,
, throwe.
try..catch.
try..catch( ), .
catch SyntaxError,
:
vardata='{"name":"","age":30}';//
try{
varuser=JSON.parse(data);
if(!user.name){
thrownewSyntaxError("");
}
blabla();//
alert(user.name);
}catch(e){
if(e.name=="SyntaxError"){
alert(",");
}else{
throwe;
}
}
, , catch, ,
.
,
try..catch:
functionreadData(){
vardata='{"name":"","age":30}';
try{
//...
blabla();//!
}catch(e){
//...
if(e.name!='SyntaxError'){
throwe;//
}
}
}
try{
readData();
}catch(e){
alert("catch:"+e);//
}
, , . ,
, - .
readData .
, SyntaxError, , , , URIError(
URI), .
, readData, , .
:
, , ?
, ,
, . , ,
, , .
, .
, .
, ,
ReadError, .
, cause(. ).
:
functionReadError(message,cause){
this.message=message;
this.cause=cause;
this.name='ReadError';
this.stack=cause.stack;
}
functionreadData(){
vardata='{baddata}';
try{
//...
JSON.parse(data);
//...
}catch(e){
//...
if(e.name=='URIError'){
thrownewReadError("URI",e);
}elseif(e.name=='SyntaxError'){
thrownewReadError("",e);
}else{
throwe;//
}
}
}
try{
readData();
}catch(e){
if(e.name=='ReadError'){
alert(e.message);
alert(e.cause);//
}else{
throwe;
}
}
,
ReadError, .
finally
try..catch : finally.
:
r
y
{
t
....
c
a
t
c
h
(e){
}
....
f
i
n
a
l
l
y
{
}
....
}
finally , , :
try, ,
catch, .
?
try{
alert('try');
if(confirm('?'))BAD_CODE();
}catch(e){
alert('catch');
}finally{
alert('finally');
}
:
1. ? , try>catch>
finally.
2. , try>finally.
finally,
.
, sum(n),
1 n :
functionsum(n){
returnn?(n+sum(n1)):0;
}
varn=+prompt('n?',100);
varstart=newDate();
try{
varresult=sum(n);
}catch(e){
result=0;
}finally{
vardiff=newDate()start;
}
alert(result?result:'');
alert(""+diff);
finally,
sum .
, n=100 , finally
try, n=100000 - ,
finally catch.
finally return
finally try..catch, return.
, try return, finally ,
.
functionfunc(){
try{
//
return1;
}catch(e){
/*...*/
}finally{
alert('finally');
}
}
alert(func());//finally,1
try - ,
, finally .
, try..finally catch:
functionfunc(){
try{
return1;
}finally{
alert('');
}
}
alert(func());//finally,1
try..finally .
try , return.
: window.onerror
, try..catch try..catch,
. .
- , ? , .
window.onerror, ,
, URL ,
.
, .
:
<script>
window.onerror=function(message,url,lineNumber){
alert(",!\n"+
":"+message+"\n("+url+":"+lineNumber+")");
};
functionreadData(){
error();//,
}
readData();
</script>
, window.onerror ,
, , , ,
.
-,
, : https://errorception.com/
http://www.muscula.com/ .
.
JavaScript :
try..catch..finally
.
,
, , .
, , JSON.parse(str)
. try..catch
.
:
r
y
{
t
....
c
a
t
c
h
(e){
}
....
f
i
n
a
l
l
y
{
}
....
}
try..catch try..finally.
throwerr , err
, Error, message name.
, :
catch(err) ,
, throwerr.
, , , , name.
,
, , ,
. , , ,
, , .
.
window.onerror ,
. , ,
.
Finally ?
: 5
.
1. finally try..catch:
try{
}catch(e){
}finally{
:
}
2. try..catch:
try{
}catch(e){
}
:
, try..catch,
, . finally-
?
, finally , .
Eval-
: 5
, ( prompt)
eval.
.
, 2+, ,
NaN, 0/0.
,
JavaScript.
, .
- (),
.
-
, , , (
) , , .
, , ,
, .
JavaScript .
, Math
( Math.PI).
(Math.sin, Math.pow, )
, . , Math
, Math.
-, :
functionUser(name){
this.sayHi=function(){
alert(","+name);
};
}
varvasya=newUser("");//
vasya.sayHi();//""
User().
, , User.
- / ,
.
JavaScript -. , User
. .
, . ,
SOLID .
- , :
- .
..
- . .
, . , . , . .
,
. , , , ,
.
.
hello world.
, .
, , , .
.
, . : , , , , ,
:)
( )
. , .
- , ? ,
- .
,
.
, (
?) ( ).
, .
, , ,
.
:
,
, (
, ).
, ,
.
, :
, ,
.
,
. ,
.
, .
. .
, , .
.
.
JavaScript .
, , ,
.
1:
CoffeeMachine.
functionCoffeeMachine(power){
this.waterAmount=0;//
alert(':'+power+'');
}
//
varcoffeeMachine=newCoffeeMachine(100);
//
coffeeMachine.waterAmount=200;
, ,
.
power ,
.
,
.
, this, .
waterAmount ,
. .
power ,
.
, , .
/, /
.
.
- ,
,
, .
2:
run, ,
getBoilTime onReady:
functionCoffeeMachine(power){
this.waterAmount=0;
//
functiongetBoilTime(){
return1000;//
}
//
functiononReady(){
alert('!');
}
this.run=function(){
//setTimeout,
//onReadygetBoilTime()
setTimeout(onReady,getBoilTime());
};
}
varcoffeeMachine=newCoffeeMachine(100);
coffeeMachine.waterAmount=200;
coffeeMachine.run();
, onReady, getBoilTime
.
, ( )
, .
3:
c*m*T/power, :
c , 4200.
m , .
T , , ,
20, 100 T=80.
power .
getBoilTime(),
:
"usestrict"
functionCoffeeMachine(power){
this.waterAmount=0;
//getBoilTime
varWATER_HEAT_CAPACITY=4200;
//
functiongetBoilTime(){
returnthis.waterAmount*WATER_HEAT_CAPACITY*80/power;//!
}
//
functiononReady(){
alert('!');
}
this.run=function(){
setTimeout(onReady,getBoilTime());
};
}
varcoffeeMachine=newCoffeeMachine(1000);
coffeeMachine.waterAmount=200;
coffeeMachine.run();
WATER_HEAT_CAPACITY ,
.
, getBoilTime . ,
?
4:
: getBoilTime(). this?
, undefined( window), -
this.waterAmount !
, getBoilTime :
getBoilTime.call(this):
functionCoffeeMachine(power){
this.waterAmount=0;
varWATER_HEAT_CAPACITY=4200;
functiongetBoilTime(){
returnthis.waterAmount*WATER_HEAT_CAPACITY*80/power;
}
functiononReady(){
alert('!');
}
this.run=function(){
setTimeout(onReady,getBoilTime.call(this));
};
}
//,100000W
varcoffeeMachine=newCoffeeMachine(100000);
coffeeMachine.waterAmount=200;
coffeeMachine.run();
, - . , ,
getBoilTime, , ..
getBoilTime.call(this).
.
bind
getBoilTime bind,
:
functionCoffeeMachine(power){
this.waterAmount=0;
varWATER_HEAT_CAPACITY=4200;
vargetBoilTime=function(){
returnthis.waterAmount*WATER_HEAT_CAPACITY*80/power;
}.bind(this);
functiononReady(){
alert('!');
}
this.run=function(){
setTimeout(onReady,getBoilTime());
};
}
varcoffeeMachine=newCoffeeMachine(100000);
coffeeMachine.waterAmount=200;
coffeeMachine.run();
, call.
.
this
, ,
this
.
:
functionCoffeeMachine(power){
this.waterAmount=0;
varWATER_HEAT_CAPACITY=4200;
varself=this;
functiongetBoilTime(){
returnself.waterAmount*WATER_HEAT_CAPACITY*80/power;
}
functiononReady(){
alert('!');
}
this.run=function(){
setTimeout(onReady,getBoilTime());
};
}
varcoffeeMachine=newCoffeeMachine(100000);
coffeeMachine.waterAmount=200;
coffeeMachine.run();
getBoilTime self .
, , self, ,
,
self this.
self , varme=this.
,
.
.
, :
, .
, , , ,
, .
.
, , - ,
. , , , ,
.
, , , , ,
.
. ,
.
, , ..
, .
,
, .
, , ( )
, , , ,
.
,
. ,
- , .
, . .
.
, , ,
.
: 5
, :
stop(), ( clearTimeout).
functionCoffeeMachine(power){
this.waterAmount=0;
varWATER_HEAT_CAPACITY=4200;
varself=this;
functiongetBoilTime(){
returnself.waterAmount*WATER_HEAT_CAPACITY*80/power;
}
functiononReady(){
alert('!');
}
this.run=function(){
setTimeout(onReady,getBoilTime());
};
}
:
varcoffeeMachine=newCoffeeMachine(50000);
coffeeMachine.waterAmount=200;
coffeeMachine.run();
coffeeMachine.stop();//
P.S. . P.P.S. ,
, timerId,
.
,
.
waterAmount:
functionCoffeeMachine(power){
//
this.waterAmount=0;
...
}
. ,
.
//!
coffeeMachine.waterAmount=1000000;
, , , :
//,!
coffeeMachine.waterAmount=1000000;
, .
,
.
,
, (setter
method).
set, ,
setWaterAmount:
functionCoffeeMachine(power,capacity){//capacity
varwaterAmount=0;
varWATER_HEAT_CAPACITY=4200;
functiongetTimeToBoil(){
returnwaterAmount*WATER_HEAT_CAPACITY*80/power;
}
//""
this.setWaterAmount=function(amount){
if(amount<0){
thrownewError("");
}
if(amount>capacity){
thrownewError(","+capacity);
}
waterAmount=amount;
};
functiononReady(){
alert('!');
}
this.run=function(){
setTimeout(onReady,getTimeToBoil());
};
}
varcoffeeMachine=newCoffeeMachine(1000,500);
coffeeMachine.setWaterAmount(600);//,!
waterAmount , ( ), , ,
.
, ,
(getter method).
get, getWaterAmount:
functionCoffeeMachine(power,capacity){
//...
this.setWaterAmount=function(amount){
if(amount<0){
thrownewError("");
}
if(amount>capacity){
thrownewError(","+capacity);
}
waterAmount=amount;
};
this.getWaterAmount=function(){
returnwaterAmount;
};
}
varcoffeeMachine=newCoffeeMachine(1000,500);
coffeeMachine.setWaterAmount(450);
alert(coffeeMachine.getWaterAmount());//450
-
, ,
.
,
.
:
functionCoffeeMachine(power,capacity){
varwaterAmount=0;
this.waterAmount=function(amount){
//,,
if(!arguments.length)returnwaterAmount;
//
if(amount<0){
thrownewError("");
}
if(amount>capacity){
thrownewError(","+capacity);
}
waterAmount=amount;
};
}
varcoffeeMachine=newCoffeeMachine(1000,500);
//
coffeeMachine.waterAmount(450);
alert(coffeeMachine.waterAmount());//450
- , ,
JavaScript-, jQuery D3
.
,
- -, ,
.
, ,
.
/ ,
, .
/ , ,
.
: 4
User :
firstName surname.
.
getFullName(), .
:
functionUser(){
/**/
}
varuser=newUser();
user.setFirstName("");
user.setSurname("");
alert(user.getFullName());//
power
: 5
power,
.
:
functionCoffeeMachine(power,capacity){
//...
this.setWaterAmount=function(amount){
if(amount<0){
thrownewError("");
}
if(amount>capacity){
thrownewError(","+capacity);
}
waterAmount=amount;
};
this.getWaterAmount=function(){
returnwaterAmount;
};
}
, , power ,
.
, power
, .
: 5
addWater(amount), .
, ,
.
:
functionCoffeeMachine(power,capacity){
varwaterAmount=0;
varWATER_HEAT_CAPACITY=4200;
functiongetTimeToBoil(){
returnwaterAmount*WATER_HEAT_CAPACITY*80/power;
}
this.setWaterAmount=function(amount){
if(amount<0){
thrownewError("");
}
if(amount>capacity){
thrownewError(","+capacity);
}
waterAmount=amount;
};
functiononReady(){
alert('!');
}
this.run=function(){
setTimeout(onReady,getTimeToBoil());
};
}
:
varcoffeeMachine=newCoffeeMachine(100000,400);
coffeeMachine.addWater(200);
coffeeMachine.addWater(100);
coffeeMachine.addWater(300);//,400
coffeeMachine.run();
onReady
: 5
, - , .
onReady, :
functionCoffeeMachine(power,capacity){
varwaterAmount=0;
varWATER_HEAT_CAPACITY=4200;
functiongetTimeToBoil(){
returnwaterAmount*WATER_HEAT_CAPACITY*80/power;
}
this.setWaterAmount=function(amount){
//...
waterAmount=amount;
};
this.getWaterAmount=function(amount){
returnwaterAmount;
};
functiononReady(){
alert('!');
}
this.run=function(){
setTimeout(onReady,getTimeToBoil());
};
}
setOnReady, onReady, :
varcoffeeMachine=newCoffeeMachine(20000,500);
coffeeMachine.setWaterAmount(150);
coffeeMachine.setOnReady(function(){
varamount=coffeeMachine.getWaterAmount();
alert(':'+amount+'');//:150
});
coffeeMachine.run();
P.S. onReady , .
P.P.S. , setOnReady ,
, onReady
.
isRunning
: 5
.
isRunning(), true,
false, .
, :
varcoffeeMachine=newCoffeeMachine(20000,500);
coffeeMachine.setWaterAmount(100);
alert(':'+coffeeMachine.isRunning());//:false
coffeeMachine.run();
alert(':'+coffeeMachine.isRunning());//:true
coffeeMachine.setOnReady(function(){
alert(":"+coffeeMachine.isRunning());//:false
});
.
JavaScript ,
, .
?
. .
? ,
, , .
. ,
, ..
, ,
.
, , - ,
.
, ,
, , :
, ..
-
- , ,
. - .
,
.
Machine
Machine
enable() disable():
functionMachine(){
varenabled=false;
this.enable=function(){
enabled=true;
};
this.disable=function(){
enabled=false;
};
}
. :
functionCoffeeMachine(power){
Machine.call(this);//
varwaterAmount=0;
this.setWaterAmount=function(amount){
waterAmount=amount;
};
}
varcoffeeMachine=newCoffeeMachine(10000);
coffeeMachine.enable();
coffeeMachine.setWaterAmount(100);
coffeeMachine.disable();
Machine.call(this)
CoffeeMachine.
Machine, this .
Machine, , this ,
this.enable this.disable.
CoffeeMachine
.
coffeeMachine, Machine
CoffeeMachine.
.
.
, enabled, :
functionMachine(){
varenabled=false;
this.enable=function(){
enabled=true;
};
this.disable=function(){
enabled=false;
};
}
functionCoffeeMachine(power){
Machine.call(this);
this.enable();
//,!
alert(enabled);
}
varcoffeeMachine=newCoffeeMachine(10000);
, enabled Machine.
.
, this.
, , ,
_.
functionMachine(){
this._enabled=false;//varenabled
this.enable=function(){
this._enabled=true;
};
this.disable=function(){
this._enabled=false;
};
}
functionCoffeeMachine(power){
Machine.call(this);
this.enable();
alert(this._enabled);//true
}
varcoffeeMachine=newCoffeeMachine(10000);
, ,
.
.
, , , ,
.
CoffeeMachine power.
Machine, ,
.
functionMachine(power){
this._power=power;//(1)
this._enabled=false;
this.enable=function(){
this._enabled=true;
};
this.disable=function(){
this._enabled=false;
};
}
functionCoffeeMachine(power){
Machine.apply(this,arguments);//(2)
alert(this._enabled);//false
alert(this._power);//10000
}
varcoffeeMachine=newCoffeeMachine(10000);
Machine power. ,
(1).
.
(2) Machine.call(this), :
Machine.apply(this,arguments), Machine
.
Machine.call(this,power),
apply ,
.
, CoffeeMachine, Machine.
Machine Fridge,
MicroOven ,
, /.
Machine , .
//Fridge,
//Machine
functionFridge(power,temperature){
Machine.apply(this,arguments);
//...
}
,
.
, , CoffeeMachine enable:
functionCoffeeMachine(power,capacity){
Machine.apply(this,arguments);
//this.enable
this.enable=function(){
/*enable*/
};
}
, , , ,
-. , , .
,
enable , :
functionCoffeeMachine(power){
Machine.apply(this,arguments);
varparentEnable=this.enable;//(1)
this.enable=function(){//(2)
parentEnable.call(this);//(3)
this.run();//(4)
}
...
}
( ):
1. this.enable ,
parentEnable.
2. this.enable
3. - parentEnable.
4. - , .
(3).
: parentEnable.call(this).
: parentEnable(), this .
, parentEnable(),
, , bind
, , this,
, :
functionMachine(power){
this._enabled=false;
varself=this;
this.enable=function(){
//this
self._enabled=true;
};
this.disable=function(){
self._enabled=false;
};
}
functionCoffeeMachine(power){
Machine.apply(this,arguments);
varwaterAmount=0;
this.setWaterAmount=function(amount){
waterAmount=amount;
};
varparentEnable=this.enable;
this.enable=function(){
parentEnable();//,this
this.run();
}
functiononReady(){
alert('!');
}
this.run=function(){
setTimeout(onReady,1000);
};
}
varcoffeeMachine=newCoffeeMachine(10000);
coffeeMachine.setWaterAmount(50);
coffeeMachine.enable();
parentEnable=this.enable
. , self.
, ,
.
():
1. Machine. (private),
(public) (protected) :
functionMachine(params){
//Machine
varprivateProperty;
//
this.publicProperty=...;
//Machine
//
this._protectedProperty=...
}
varmachine=newMachine(...)
machine.public();
2. apply.
:
functionCoffeeMachine(params){
//
Machine.apply(this,arguments);
this.coffeePublicProperty=...
}
varcoffeeMachine=newCoffeeMachine(...);
coffeeMachine.publicProperty();
coffeeMachine.coffeePublicProperty();
3. CoffeeMachine, , .
, .
:
functionCoffeeMachine(params){
Machine.apply(this,arguments);
varparentProtected=this._protectedProperty;
this._protectedProperty=function(args){
parentProtected.apply(this,args);//(*)
//...
};
}
(*) parentProtected(args),
this, , , varself=this:
functionMachine(params){
varself=this;
this._protected=function(){
self.property="value";
};
}
, , , .
,
.
,
, / .
: 5
CoffeeMachine , run ,
.
:
varcoffeeMachine=newCoffeeMachine(10000);
coffeeMachine.run();//,!
:
varcoffeeMachine=newCoffeeMachine(10000);
coffeeMachine.enable();
coffeeMachine.run();//...!
: 5
.
, :
varcoffeeMachine=newCoffeeMachine(10000);
coffeeMachine.enable();
coffeeMachine.run();
coffeeMachine.disable();//,
: 4
Fridge(power), Machine,
food addFood(...), getFood():
food .
addFood(item) food ,
addFood(item1,item2...)
.
, , .
power/100, power
, .
getFood() ,
food.
:
varfridge=newFridge(200);
fridge.addFood("");//,
:
//500(5)
varfridge=newFridge(500);
fridge.enable();
fridge.addFood("");
fridge.addFood("","");
fridge.addFood("","","");//,
:
varfridge=newFridge(500);
fridge.enable();
fridge.addFood("");
fridge.addFood("","");
varfridgeFood=fridge.getFood();
alert(fridgeFood);//,,
//
fridgeFood.push("","");
alert(fridge.getFood());//:,,
Machine, :
functionMachine(power){
this._power=power;
this._enabled=false;
varself=this;
this.enable=function(){
self._enabled=true;
};
this.disable=function(){
self._enabled=false;
};
}
: 5
:
filterFood(func), , func(item)
==true
removeFood(item), item .
:
varfridge=newFridge(500);
fridge.enable();
fridge.addFood({
title:"",
calories:100
});
fridge.addFood({
title:"",
calories:30
});
fridge.addFood({
title:"",
calories:10
});
fridge.addFood({
title:"",
calories:150
});
fridge.removeFood("");//
alert(fridge.getFood().length);//4
vardietItems=fridge.filterFood(function(item){
returnitem.calories<50;
});
dietItems.forEach(function(item){
alert(item.title);//,
fridge.removeFood(item);
});
alert(fridge.getFood().length);//2
disable
: 5
disable,
.
:
varfridge=newFridge(500);
fridge.enable();
fridge.addFood("");
fridge.disable();//,
- JavaScript.
JavaScript , ,
.
__proto__.
__proto__
__proto__ ,
, , __proto__.
__proto__ , IE10-, IE ,
, , , ,
.
( IE10-):
varanimal={
eats:true
};
varrabbit={
jumps:true
};
rabbit.__proto__=animal;
//rabbit
alert(rabbit.jumps);//true
alert(rabbit.eats);//true
1. alert jumps
rabbit.
2. alert rabbit.eats, rabbit,
rabbit.__proto__, , , animal.
rabbit.eats( ):
, __proto__, .
, animal rabbit.
, rabbit animal.
. ,
, rabbit.eats=value deleterabbit.eats
.
rabbit, alert
, :
varanimal={
eats:true
};
varrabbit={
jumps:true,
eats:false
};
rabbit.__proto__=animal;
alert(rabbit.eats);//false,rabbit
, ,
.
, __proto__, __proto__, , .
.
__proto__
EcmaScript __proto__
[[Prototype]].
,
, prototype, .
hasOwnProperty
for..in .
, :
varanimal={
eats:true
};
varrabbit={
jumps:true,
__proto__:animal
};
for(varkeyinrabbit){
alert(key+"="+rabbit[key]);//"eats""jumps"
}
, , .
obj.hasOwnProperty(prop) true, prop
obj, false.
:
varanimal={
eats:true
};
varrabbit={
jumps:true,
__proto__:animal
};
alert(rabbit.hasOwnProperty('jumps'));//true:jumpsrabbit
alert(rabbit.hasOwnProperty('eats'));//false:eats
, , key
hasOwnProperty:
varanimal={
eats:true
};
varrabbit={
jumps:true,
__proto__:animal
};
for(varkeyinrabbit){
if(!rabbit.hasOwnProperty(key))continue;//""
alert(key+"="+rabbit[key]);//"jumps"
}
__proto__
__proto__.
, __proto__? -, ,
.
: Object.getPrototypeOf(obj)
obj.__proto__( IE8-)
: Object.setPrototypeOf(obj, proto)
obj.__proto__=proto( IE10-).
, :
: Object.create(proto, descriptors)
__proto__, ( IE8-),
.
JavaScript
__proto__.
rabbit.__proto__=animal, animal
rabbit.
, , __proto__.
. obj.prop=
deleteobj.prop obj.
,
, __proto__, ,
.
:
Object.getPrototypeOf(obj)
( IE8-)
Object.setPrototypeOf(obj, proto)
Object.create(proto, descriptors)
( IE10-)
( IE8-)
, __proto__ IE. .
__proto__, ,
.
, __proto__ JavaScript
.
c delete?
: 5
?
varanimal={
jumps:null
};
varrabbit={
jumps:true
};
rabbit.__proto__=animal;
alert(rabbit.jumps);//?(1)
deleterabbit.jumps;
alert(rabbit.jumps);//?(2)
deleteanimal.jumps;
alert(rabbit.jumps);//?(3)
this
: 5
rabbit.eat()?
, full: rabbit animal?
varanimal={
eat:function(){
this.full=true;
}
};
varrabbit={
__proto__:animal
};
rabbit.eat();
: 5
:
varhead={
glasses:1
};
vartable={
pen:3
};
varbed={
sheet:1,
pillow:2
};
varpockets={
money:2000
};
:
1. __proto__, -
pockets>bed>table>head.
pockets.pen==3, bed.glasses==1, table.money==undefined.
2. , glasses: pockets.glasses
head.glasses? .
F.prototype new
, {...}.
- new. ,
.
F.prototype
__proto__ .
, , , newRabbit, animal,
:
varanimal={
eats:true
};
functionRabbit(name){
this.name=name;
this.__proto__=animal;
}
varrabbit=newRabbit("");
alert(rabbit.eats);//true,
IE10-.
, JavaScript ,
- .
,
prototype.
new, __proto__ prototype
-.
, , :
varanimal={
eats:true
};
functionRabbit(name){
this.name=name;
}
Rabbit.prototype=animal;
varrabbit=newRabbit("");//rabbit.__proto__==animal
alert(rabbit.eats);//true
Rabbit.prototype=animal :
newRabbit __proto__=animal.
prototype
prototype , ,
-.
, new, ,
__proto__ .
prototype
, .
, new, prototype ,
. , , .
constructor
prototype.
:
functionRabbit(){}
Rabbit.prototype={
constructor:Rabbit
};
Rabbit.prototype, .
:
functionRabbit(){}
//Rabbit.prototype:constructor
alert(Object.getOwnPropertyNames(Rabbit.prototype));//constructor
//Rabbit
alert(Rabbit.prototype.constructor==Rabbit);//true
, :
functionRabbit(name){
this.name=name;
alert(name);
}
varrabbit=newRabbit("");
varrabbit2=newrabbit.constructor("");
, , , ,
(, ), .
constructor
JavaScript constructor. , ,
. .
, Rabbit.prototype={jumps:true} constructor
.
JavaScript ,
. , , ,
, constructor:
Rabbit.prototype={
jumps:true,
constructor:Rabbit
};
prototype :
//constructor
Rabbit.prototype.jumps=true
Object.create IE8 , , -
F.prototype.
.
IE,
Object.create(proto) , prototype.
, .
- inherit, :
functioninherit(proto){
functionF(){}
F.prototype=proto;
varobject=newF;
returnobject;
}
inherit(animal) Object.create(animal).
animal.
:
varanimal={
eats:true
};
varrabbit=inherit(animal);
alert(rabbit.eats);//true
inherit , , ,
- , :
functioninherit(proto){
functionF(){}//(1)
F.prototype=proto//(2)
varobject=newF;//(3)
returnobject;//(4)
}
1. F. this, newF,
.
2. F.prototype proto
3. newF __proto__ F.prototype.
4. , . .
, Object.create -:
if(!Object.create)Object.create=inherit;/*inherit*/
, es5-shim
Object.create .
Constructor, :
__proto__ , newConstructor,
Constructor.prototype.
Constructor.prototype
constructor, Constructor. ,
, . , JavaScript
, .
Object.create(proto) prototype,
, IE8-.
: 5
newRabbit, prototype.
? ?
. ?
functionRabbit(){}
Rabbit.prototype={
eats:true
};
varrabbit=newRabbit();
alert(rabbit.eats);
(), ?
functionRabbit(){}
Rabbit.prototype={
eats:true
};
varrabbit=newRabbit();
Rabbit.prototype={};
alert(rabbit.eats);
? ( ):
functionRabbit(name){}
Rabbit.prototype={
eats:true
};
varrabbit=newRabbit();
Rabbit.prototype.eats=false;
alert(rabbit.eats);
? ( )
functionRabbit(name){}
Rabbit.prototype={
eats:true
};
varrabbit=newRabbit();
deleterabbit.eats;//(*)
alert(rabbit.eats);
:
functionRabbit(name){}
Rabbit.prototype={
eats:true
};
varrabbit=newRabbit();
deleteRabbit.prototype.eats;//(*)
alert(rabbit.eats);
: 4
Menu, options:
/*options:width,height..*/
functionMenu(options){
...
}
.
options:
functionMenu(options){
options.width=options.width||300;//300
...
}
, .. options
. Menu ,
, .
options . options
, .
Object.create ,
.
?
: 5
, :
functionRabbit(name){
this.name=name;
}
Rabbit.prototype.sayHi=function(){
alert(this.name);
}
varrabbit=newRabbit("Rabbit");
?
rabbit.sayHi();
Rabbit.prototype.sayHi();
Object.getPrototypeOf(rabbit).sayHi();
rabbit.__proto__.sayHi();
-? ?
: 5
obj, - ,
, .
?
varobj2=newobj.constructor();
obj,
.
JavaScript
JavaScript : Date, Array, Object .
JavaScript,
{} ?
, .
varobj={};
alert(obj);//"[objectObject]"?
, alert(obj)? - .
Object.prototype
, toString, , (
), obj.__proto__, :
alert({}.__proto__.toString);//functiontoString
obj __proto__?
1. obj={} obj=newObject, Object .
2. newObject, __proto__ prototype
, Object.prototype.
3. obj.toString() Object.prototype.
varobj={};
//?
alert(obj.toString==Object.prototype.toString);//true,
//,__proto__Object.prototype?
alert(obj.__proto__==Object.prototype);//true
//__proto__Object.prototype?
alert(obj.__proto__.__proto__);//null,
JavaScript
Array, Function .
Array.prototype, Function.prototype ..
, , [1,2,3], new
Array, Array.prototype.
,
Array.prototype.__proto__, Object.prototype.
, .
( ) , .
Object.prototype , , __proto__ null.
, Object, ,
Object.prototype.
, , , -
prototype. .
, , Array toString,
:
vararr=[1,2,3]
alert(arr);//1,2,3<Array.prototype.toString
apply
, ,
[].join arguments:
functionshowList(){
alert([].join.call(arguments,""));
}
showList("","","");//
join Array.prototype, , :
functionshowList(){
alert(Array.prototype.join.call(arguments,""));
}
showList("","","");//
, [], ,
.
, :
Number.prototype, Boolean.prototype, String.prototype.
, , ,
, newString , newNumber , newBoolean
.
,
, .
:
varuser="";//()
alert(user.toUpperCase());//
//newString
//
//newString,
//:
varuser="";
user.age=30;
alert(user.age);//undefined
age , ,
.
String/Number/Boolean
, , newNumber.
. :
alert(typeof1);//"number"
alert(typeofnewNumber(1));//"object"?!?
, :
varzero=newNumber(0);
if(zero){//true,alert
alert("true?!?");
}
null undefined
null undefined . .
, ( ), ,
.
. .
,
:
String.prototype.repeat=function(times){
returnnewArray(times+1).join(this);
};
alert("".repeat(3));//
Object.prototype.each(func),
func :
Object.prototype.each=function(f){
for(varpropinthis){
varvalue=this[prop];
f.call(value,prop,value);//f(prop,value),this=value
}
}
//!(,!)
varuser={
name:'',
age:25
};
user.each(function(prop,val){
alert(prop);//name>age>(!)each
});
.
user each. , , for..in
, .
, hasOwnProperty:
Object.prototype.each=function(f){
for(varpropinthis){
//
if(!this.hasOwnProperty(prop))continue;
varvalue=this[prop];
f.call(value,prop,value);
}
};
//
varobj={
name:'',
age:25
};
obj.each(function(prop,val){
alert(prop);//name>age
});
, . hasOwnProperty
! Object.prototype,
enumerable.
, , IE8-:
Object.prototype.each=function(f){
for(varpropinthis){
varvalue=this[prop];
f.call(value,prop,value);
}
};
//,enumerable:false
Object.defineProperty(Object.prototype,'each',{
enumerable:false
});
//
varobj={
name:'',
age:25
};
obj.each(function(prop,val){
alert(prop);//name>age
});
,
.
,
,
.
,
,
,
-.
.
, - ,
.
, , ,
, .
,
, .
, Object.create(proto) :
if(!Object.create){
Object.create=function(proto){
functionF(){}
F.prototype=proto;
returnnewF;
};
}
es5-shim ,
JavaScript . .
.
.
Object.prototype, Object.defineProperty
enumerable(IE9+), for..in,
.
,
.
,
Object.create , Object.keys , Function.prototype.bind ..
es5-shim .
defer
: 5
defer(ms), ms
.
:
functionf(){
alert("");
}
f.defer(1000);//""1
defer
: 4
defer(ms), ,
ms .
, :
functionf(a,b){
alert(a+b);
}
f.defer(1000)(1,2);//31.
, .
, JavaScript , .
, .
, Animal , :
functionAnimal(name){
this.speed=0;
this.name=name;
this.run=function(speed){
this.speed+=speed;
alert(this.name+','+this.speed);
};
this.stop=function(){
this.speed=0;
alert(this.name+'');
};
};
varanimal=newAnimal('');
alert(animal.speed);//0,
animal.run(3);//,3
animal.run(10);//,13
animal.stop();//
, , ,
Object, Date .
, :
1. -.
2. , , prototype.
Animal:
//
functionAnimal(name){
this.name=name;
this.speed=0;
}
//
Animal.prototype.run=function(speed){
this.speed+=speed;
alert(this.name+','+this.speed);
};
Animal.prototype.stop=function(){
this.speed=0;
alert(this.name+'');
};
varanimal=newAnimal('');
alert(animal.speed);//0,
animal.run(5);//,5
animal.run(5);//,10
animal.stop();//
,
.
.
,
,
.
, , .
, name sayHi :
functionAnimal(name){
this.sayHi=function(){
alert(name);
};
}
varanimal=newAnimal("");
animal.sayHi();//
,
, , name
, :
functionAnimal(name){
this._name=name;
}
Animal.prototype.sayHi=function(){
alert(this._name);
}
varanimal=newAnimal("");
animal.sayHi();//
, .
this._name, .
: 5
CoffeeMachine, .
: CoffeeMachine .
:
functionCoffeeMachine(power){
varwaterAmount=0;
varWATER_HEAT_CAPACITY=4200;
functiongetTimeToBoil(){
returnwaterAmount*WATER_HEAT_CAPACITY*80/power;
}
this.run=function(){
setTimeout(function(){
alert('!');
},getTimeToBoil());
};
this.setWaterAmount=function(amount){
waterAmount=amount;
};
}
varcoffeeMachine=newCoffeeMachine(10000);
coffeeMachine.setWaterAmount(50);
coffeeMachine.run();
P.S. ,
.
__proto__
: 5
, , .
( "Hamster").
- food found,
.
. , -
.
? ?
functionHamster(){}
Hamster.prototype.food=[];//""
Hamster.prototype.found=function(something){
this.food.push(something);
};
//
speedy=newHamster();
lazy=newHamster();
speedy.found("");
speedy.found("");
alert(speedy.food.length);//2
alert(lazy.food.length);//2(!??)
JavaScript
JavaScript, , __proto__.
, , ,
, newAdmin, , ,
newUser, - .
Array Object
,
JavaScript.
Array, Object:
Array Array.prototype.
Array.prototype Object.prototype.
Array
, Array.prototype.slice.
, , hasOwnProperty, Array.prototype,
Object.prototype.
console.dir([1,2,3]).
Chrome :
, length , __proto__
concat, Array.prototype, Object.prototype.
console.dir
, console.dir, console.log, log
, .
: Rabbit,
Animal.
, .
Animal:
functionAnimal(name){
this.name=name;
this.speed=0;
}
Animal.prototype.run=function(speed){
this.speed+=speed;
alert(this.name+','+this.speed);
};
Animal.prototype.stop=function(){
this.speed=0;
alert(this.name+'');
};
Rabbit:
functionRabbit(name){
this.name=name;
this.speed=0;
}
Rabbit.prototype.jump=function(){
this.speed++;
alert(this.name+'');
};
varrabbit=newRabbit('');
, , rabbit=newRabbit
Rabbit.prototype, , ,
Animal.prototype.
: rabbit>
Rabbit.prototype>Animal.prototype, ,
.
__proto__ Rabbit.prototype Animal.prototype.
:
Rabbit.prototype.__proto__=Animal.prototype;
, __proto__ IE10-,
Object.create.
.
Animal , Rabbit.prototype ,
Object.create:
functionRabbit(name){
this.name=name;
this.speed=0;
}
//
Rabbit.prototype=Object.create(Animal.prototype);
//(...)
Rabbit.prototype.jump=function(){...};
Rabbit.prototype=Object.create(Animal.prototype);
Rabbit.prototype.constructor=Rabbit;
Animal Rabbit:
//1.Animal
functionAnimal(name){
this.name=name;
this.speed=0;
}
//1.1.
Animal.prototype.stop=function(){
this.speed=0;
alert(this.name+'');
}
Animal.prototype.run=function(speed){
this.speed+=speed;
alert(this.name+','+this.speed);
};
//2.Rabbit
functionRabbit(name){
this.name=name;
this.speed=0;
}
//2.1.
Rabbit.prototype=Object.create(Animal.prototype);
Rabbit.prototype.constructor=Rabbit;
//2.2.Rabbit
Rabbit.prototype.jump=function(){
this.speed++;
alert(this.name+','+this.speed);
}
, , .
: Rabbit.prototype=Object.create(proto)
, .
: Rabbit.prototype=newAnimal
Object.create(Animal.prototype)
newAnimal, :
//Rabbit.prototype=Object.create(Animal.prototype)
Rabbit.prototype=newAnimal();
, , , newAnimal
Animal.prototype, Object.create(Animal.prototype).
.
. Animal,
!
, ,
, - , .
Object.create.
Animal Rabbit :
functionAnimal(name){
this.name=name;
this.speed=0;
}
functionRabbit(name){
this.name=name;
this.speed=0;
}
, Rabbit ,
Animal.
, Animal,
:
functionRabbit(name){
Animal.apply(this,arguments);
}
Animal , ,
this, .
Animal.call(this,name), apply,
.
, Rabbit Animal. - Rabbit.prototype
Animal.prototype.
Rabbit - , . ,
, , run():
Rabbit.prototype.run=function(speed){
this.speed++;
this.jump();
};
rabbit.run() run :
,
. , , ,
.
, :
Rabbit.prototype.run=function(){
//,
Animal.prototype.run.apply(this,arguments);
this.jump();
}
apply .
Animal.prototype.run(), this run
Animal.prototype, , .
, (Child.prototype)
(Parent.prototype).
Object.create:
:
Rabbit.prototype=Object.create(Animal.prototype);
, , ,
, apply(this,arguments), :
functionRabbit(...){
Animal.apply(this,arguments);
}
, ,
:
Rabbit.prototype.run=function(){
varresult=Animal.prototype.run.apply(this,...);
//result
}
//
//
functionAnimal(name){
this.name=name;
this.speed=0;
}
//
Animal.prototype.run=function(){
alert(this.name+"!")
}
//
//
functionRabbit(name){
Animal.apply(this,arguments);
}
//
Rabbit.prototype=Object.create(Animal.prototype);
//constructor
Rabbit.prototype.constructor=Rabbit;
//
Rabbit.prototype.run=function(){
//
Animal.prototype.run.apply(this);
alert(this.name+"!");
};
//,
varrabbit=newRabbit('');
rabbit.run();
, .
, , .
- , .
- , ,
.
, Rabbit
Animal.apply(this,arguments), Animal.apply
: --!, :
functionAnimal(){
this.walk=function(){
alert('walk')
};
alert('!');
}
functionRabbit(){
Animal.apply(this,arguments);//,walk?
}
, newRabbit
. .
. ES6,
, babeljs .
: 5
. ?
functionAnimal(name){
this.name=name;
}
Animal.prototype.walk=function(){
alert(""+this.name);
};
functionRabbit(name){
this.name=name;
}
Rabbit.prototype=Animal.prototype;
Rabbit.prototype.walk=function(){
alert("!:"+this.name);
};
: 5
. ?
functionAnimal(name){
this.name=name;
this.walk=function(){
alert(""+this.name);
};
}
functionRabbit(name){
Animal.apply(this,arguments);
}
Rabbit.prototype=Object.create(Animal.prototype);
Rabbit.prototype.walk=function(){
alert(""+this.name);
};
varrabbit=newRabbit("");
rabbit.walk();
: 5
, -.
timer, template render.
: . .
P.S. ( , ).
.
: 5
. , ,
precision, setInterval. :
1000.
Clock . extendedclock.js.
Clock .
.
Clock .
P.S. ( , ).
.
: 5
Menu. : STATE_OPEN STATE_CLOSED.
AnimatingMenu, STATE_ANIMATING.
open() STATE_ANIMATING, 1 , ,
open().
close() ( open)
close.
showState "",
.
,
.
constructor?
: 5
: Animal>Rabbit.
rabbit.constructor? alert Rabbit?
functionAnimal(){}
functionRabbit(){}
Rabbit.prototype=Object.create(Animal.prototype);
varrabbit=newRabbit();
alert(rabbit.constructor==Rabbit);//?
: instanceof
instanceof , ,
.
instanceof
objinstanceofConstructor true, Constructor
.
:
functionRabbit(){}
//
varrabbit=newRabbit();
//Rabbit?
alert(rabbitinstanceofRabbit);//true,
JavaScript, . ,
!
objinstanceofConstructor:
1. obj.__proto__
2. obj.__proto__ Constructor.prototype
3. , obj obj.__proto__ 2
, ( true),
( false).
rabbitinstanceofRabbit, , :
rabbit.__proto__==Rabbit.prototype.
arrinstanceofObject, ,
arr.__proto__.__proto__==Object.prototype.
, - !
.
prototype,
:
//rabbit,
functionRabbit(){}
varrabbit=newRabbit();
//prototype...
Rabbit.prototype={};
//...instanceof!
alert(rabbitinstanceofRabbit);//false
, , prototype?
, .
: instanceof
instanceof , .
, ,
, . instanceofArray
false.
, window.
, ,
[[Class]], :
[[Class]], instanceof .
instanceof
: 5
instanceof true, a B()?
functionA(){}
functionB(){}
A.prototype=B.prototype={};
vara=newA();
alert(ainstanceofB);//true
instanceof?
: 5
: Animal>Rabbit.
instanceof?
rabbit Animal, Rabbit Object?
functionAnimal(){}
functionRabbit(){}
Rabbit.prototype=Object.create(Animal.prototype);
varrabbit=newRabbit();
alert(rabbitinstanceofRabbit);
alert(rabbitinstanceofAnimal);
alert(rabbitinstanceofObject);
, Error
, .
, ,
instanceof.
readUser(json), JSON
. , , ,
. , JSON, - ,
JSON.
json : {"name":"","age":30}.
readUser . , SyntaxError
JSON.
, PropertyError ,
name age.
PropertyError:
functionPropertyError(property){
this.name="PropertyError";
this.property=property;
this.message=""+property;
if(Error.captureStackTrace){
Error.captureStackTrace(this,PropertyError);
}else{
this.stack=(newError()).stack;
}
}
PropertyError.prototype=Object.create(Error.prototype);
, :
name .
.
message .
, PropertyError Error( ),
. , property,
.
message, property.
, Error,
.
stack , .
Error , :
functionf(){
alert(newError().stack);
}
f();//,,
, .
- .
JavaScript ,
newError, .
:
Error.captureStackTrace(this,PropertyError);
this( ) ,
, , ,
.
PropertyError.
, ,
, , , .
JavaScript.
, , .
Error.call(this,message).
, Error , this.message
( name stack) . .
instanceof + try..catch =
readUser:
//
functionPropertyError(property){
this.name="PropertyError";
this.property=property;
this.message=""+property;
if(Error.captureStackTrace){
Error.captureStackTrace(this,PropertyError);
}else{
this.stack=(newError()).stack;
}
}
PropertyError.prototype=Object.create(Error.prototype);
//
functionreadUser(data){
varuser=JSON.parse(data);
if(!user.age){
thrownewPropertyError("age");
}
if(!user.name){
thrownewPropertyError("name");
}
returnuser;
}
//try..catch
try{
varuser=readUser('{"age":25}');
}catch(err){
if(errinstanceofPropertyError){
if(err.property=='name'){
//,
alert(",!");
}else{
alert(err.message);//...
}
}elseif(errinstanceofSyntaxError){
alert(":"+err.message);
}else{
throwerr;//,
}
}
PropertyError SyntaxError ,
, .
try..catch. instanceof
. , ,
PropertyError, errinstanceofPropertyError -
. , .
PropertyError .
PropertyRequiredError, , .
PropertyError, . -
:
functionPropertyRequiredError(property){
//
PropertyError.apply(this,arguments);
...
}
? , .
, this.name , Error.captureStackTrace
.
- , ?
PropertyError,
. . , constructor,
prototype ,
.
PropertyError :
functionPropertyError(property){
this.name="PropertyError";
this.property=property;
this.message=""+property;
if(Error.captureStackTrace){
r
r
o
r
.
c
a
p
t
u
r
e
S
t
a
c
k
T
r
a
c
e
(
t
h
i
s
,
t
h
i
s
.
c
o
n
s
t
r
u
c
t
o
r
);//(*)
E
}else{
this.stack=(newError()).stack;
}
}
PropertyError.prototype=Object.create(Error.prototype);
PropertyError.prototype.constructor=PropertyError;
functionPropertyRequiredError(property){
PropertyError.apply(this,arguments);
this.name='PropertyRequiredError';
this.message=''+property;
}
PropertyRequiredError.prototype=Object.create(PropertyError.prototype);
PropertyRequiredError.prototype.constructor=PropertyRequiredError;
varerr=newPropertyRequiredError("age");
//
alert(errinstanceofPropertyError);//true
message .
, Object.defineProperty.
//""
functionCustomError(message){
this.name="CustomError";
this.message=message;
if(Error.captureStackTrace){
Error.captureStackTrace(this,this.constructor);
}else{
this.stack=(newError()).stack;
}
}
CustomError.prototype=Object.create(Error.prototype);
CustomError.prototype.constructor=CustomError;
//
functionPropertyError(property){
CustomError.call(this,""+property)
this.name="PropertyError";
this.property=property;
}
PropertyError.prototype=Object.create(CustomError.prototype);
PropertyError.prototype.constructor=PropertyError;
//
functionPropertyRequiredError(property){
PropertyError.call(this,property);
this.name='PropertyRequiredError';
this.message=''+property;
}
PropertyRequiredError.prototype=Object.create(PropertyError.prototype);
PropertyRequiredError.prototype.constructor=PropertyRequiredError;
//
varerr=newPropertyRequiredError("age");
//
alert(errinstanceofPropertyRequiredError);//true
alert(errinstanceofPropertyError);//true
alert(errisntanceofCustomError);//true
alert(errisntanceofError);//true
SyntaxError
: 5
FormatError, SyntaxError.
, :
varerr=newFormatError("");
alert(err.message);//
alert(err.name);//FormatError
alert(err.stack);//
alert(errinstanceofSyntaxError);//true
JavaScript . __proto__ .
, ,
,
.
.
(. mixin) , - .
,
.
,
.
:
//
varsayHiMixin={
sayHi:function(){
alert(""+this.name);
},
sayBye:function(){
alert(""+this.name);
}
};
//:
functionUser(name){
this.name=name;
}
//
for(varkeyinsayHiMixin)User.prototype[key]=sayHiMixin[key];
//User""sayHi
newUser("").sayHi();//
, this
- .
- .
, .
, ,
, .
, "login",
,
.
"select"
, ,
.
. .
eventMixin, :
vareventMixin={
/**
*
*:
*menu.on('select',function(item){...}
*/
on:function(eventName,handler){
if(!this._eventHandlers)this._eventHandlers={};
if(!this._eventHandlers[eventName]){
this._eventHandlers[eventName]=[];
}
this._eventHandlers[eventName].push(handler);
},
/**
*
*menu.off('select',handler)
*/
off:function(eventName,handler){
varhandlers=this._eventHandlers&&this._eventHandlers[eventName];
if(!handlers)return;
for(vari=0;i<handlers.length;i++){
if(handlers[i]==handler){
handlers.splice(i,1);
}
}
},
/**
*
*this.trigger('select',item);
*/
trigger:function(eventName/*,...*/){
if(!this._eventHandlers||!this._eventHandlers[eventName]){
return;//
}
//
varhandlers=this._eventHandlers[eventName];
for(vari=0;i<handlers.length;i++){
handlers[i].apply(this,[].slice.call(arguments,1));
}
}
};
:
1. .on(,)
. _eventHandlers.
2. .off(,) .
3. .trigger(,) ,
, .
:
//MenueventMixin
functionMenu(){
//...
}
for(varkeyineventMixin)Menu.prototype[key]=eventMixin[key];
//select
Menu.prototype.choose=function(value){
this.trigger("select",value);
}
//
varmenu=newMenu();
//select
menu.on("select",function(value){
alert(""+value);
});
//()
menu.choose("123");
, , , ,
(this.trigger) , menu.on(...)
. ,
.
on/off/trigger ,
.
, .
. ,
, .
.
.
,
, . . ,
, .
.
, !
alert
:
<!DOCTYPEhtml>
<html>
<head>
<metacharset="utf8">
</head>
<body>
<script>
alert('JavaScript!');
</script>
</body>
</html>
alert
HTML-:
<!DOCTYPEhtml>
<html>
<head>
<metacharset="utf8">
</head>
<body>
<scriptsrc="alert.js"></script>
</body>
</html>
alert.js :
alert('JavaScript!');
:
1. big.js,
.
2. small.js, - async
, .
3. big.js, , defer,
.
?
.
, defer async . ,
, :
<script>
alert("");
</script>
, async/defer . ,
, .
, , , .
, small.js big.js ,
, ,
.
, ,
small.js big.js .
varadmin,name;//
name="";
admin=name;
alert(admin);//""
:
varourPlanetName="";//""
varuserName="";//""
, , planet name,
, .
, ,
, . ,
, , ,
.
vara=1,b=1,c,d;
//a2,
c=++a;alert(c);//2
//,
d=b++;alert(d);//1
//a3,
c=(2+++a);alert(c);//5
//b3,
d=(2+b++);alert(d);//4
//2
alert(a);//3
alert(b);//3
: x=5.
, ,
:
vara=2;
alert(a*=2);//4
x=1+4=5.
1. a^b 1, a
b( ) 1.
0 , .
2. ~ 0 1, 1 0. ,
.
,
:
functionisInteger(num){
return(num^0)===num;
}
alert(isInteger(1));//true
alert(isInteger(1.5));//false
alert(isInteger(0.5));//false
: num^0 ! , ^
. , === . num^(0===num),
.
^, |, &?
, , .
, .
, ^:
0^0 1^1 , .
0^1 1^0 1.
, .
: .
?
, 32- .
JavaScript 64- .
(52) , (11) ,
, .
, , , 52.
12345678912345 : 10110011101001110011110011100101101101011001
(44 ).
^ 32-
. ,
, , , .
:
//1000000000000000000000000000000(31)
alert(Math.pow(2,30));//1073741824
alert(Math.pow(2,30)^0);//1073741824,,
//100000000000000000000000000000000(33)
alert(Math.pow(2,32));//4294967296
alert(Math.pow(2,32)^0);//0,,
//
//10000000000000000000000000000000(32)
alert(Math.pow(2,31));//2147483648
alert(Math.pow(2,31)^0);//2147483648,,
//1
JS-:
varname=prompt("?","");
alert(name);
<!DOCTYPEhtml>
<html>
<head>
<metacharset="utf8">
</head>
<body>
<script>
varname=prompt("?","");
alert(name);
</script>
</body>
</html>
: if, '?'
if ( )
, , .. if "0".
, ( ), true.
:
if("0"){
alert('');
}
<!DOCTYPEhtml>
<html>
<body>
<script>
varvalue=prompt('""JavaScript?','');
if(value=='EcmaScript'){
alert('!');
}else{
alert('?"EcmaScript"!');
}
</script>
</body>
</html>
varvalue=prompt('',0);
if(value>0){
alert(1);
}elseif(value<0){
alert(1);
}else{
alert(0);
}
varuserName=prompt('?','');
if(userName==''){
varpass=prompt('?','');
if(pass==''){
alert('!');
}elseif(pass==null){//(*)
alert('');
}else{
alert('');
}
}elseif(userName==null){//(**)
alert('');
}else{
alert('');
}
'if' '?'
result=(a+b<4)?'':'';
'if..else' '?'
varmessage=(login=='')?'':
(login=='')?'':
(login=='')?'':
'';
alert ()?
: 2, , true.
alert(null||2||undefined);
alert ()?
: 1, 2.
alert(alert(1)||2||alert(3));
alert , , , undefined.
1. || alert(1), undefined
, .
2. 2 , ,
undefined||2 2, alert(....).
|| , alert(3) , 3
.
alert ()?
: null, .
alert(1&&null&&2);
alert ()?
: 1, undefined.
alert(alert(1)&&alert(2));
alert , , , undefined.
alert , .
?
: 3.
alert(null||2&&3||4);
&&, ||, .
:
null||2&&3||4
null||3||4
3
if
if(age>=14&&age<=90)
if
:
if(!(age>=14&&age<=90))
:
if(age<14||age>90)
if
: .
:
//
//1||0=1,true
if(1||0)alert('');
//
//1&&0=0,false
if(1&&0)alert('');
//
//&&,||
//1&&1
//:null||1&&1>null||1>1
if(null||1&&1)alert('');
""+1+0="10"//(1)
""1+0=1//(2)
true+false=1
6/"3"=2"2"*"3"=6
4+5+"px"="9px"
"$"+4+5
="$45"
"4"2
=2"4px"2
=NaN
7/0
=Infinity"9\n"+5="9\n5"
"9\n"5=14
5&&2
=2
2&&5
=5
5||0
=5
0||5=5
null+1=1//(3)
undefined+1=NaN//(4)
null=="\n0\n"=false//(5)
+null==+"\n0\n"=true//(6)
1. "+" 1 , 0.
2. "" , "" 0.
3. null 0
4. undefined NaN
5. == null , : null==
undefined .
6. == 0.
while, for
: 1.
vari=3;
while(i){
alert(i);
}
i. while(i) i=0.
, :
vari=3
alert(i);//3,i2
alert(i)//2,i1
alert(i)//1,i0
//,while(i)
i while?
1. 1 4
vari=0;
while(++i<5)alert(i);
: i=1, ++i i,
alert.
2,3,4.. .
, , ++ .
i=4 i 5, while(5<5) .
, 5 .
2. 1 5
vari=0;
while(i++<5)alert(i);
: i=1. . i++ i,
, i++<5 i=0.
alert ,
i=1.
2,3,4.. ,
, alert.
: i=4 while(4<5) ,
i++, i 5, 5 .
.
i for?
: 0 4 .
for(vari=0;i<5;++i)alert(i);
for(vari=0;i<5;i++)alert(i);
for:
1. i=0
2. i<5
3. alert(i), i++
i++ (2), i
, i++ ++i.
for(vari=2;i<=10;i++){
if(i%2==0){
alert(i);
}
}
2,
%: i%2.
for while
vari=0;
while(i<3){
alert(""+i+"!");
i++;
}
,
varnum;
do{
num=prompt("100?",0);
}while(num<=100&&num!=null);
do..while, :
1. num<=100 , 100.
2. num!=null null, ,
.
, num<=100 null true,
.
i110{
,i
,i,
,i
}
:
nextPrime:
for(vari=2;i<10;i++){
for(varj=2;j<i;j++){
if(i%j==0)continuenextPrime;
}
alert(i);//
}
, . ,
j 2 i, 2 i.
,
.
switch
if, switch
, '==='.
, , '=='.
if(browser=='IE'){
alert(',IE!');
}elseif(browser=='Chrome'
||browser=='Firefox'
||browser=='Safari'
||browser=='Opera'){
alert(',');
}else{
alert(',!');
}
: browser=='Chrome'||browser=='Firefox'...
.
switch.
if' switch
case, case:
vara=+prompt('a?','');
switch(a){
case0:
alert(0);
break;
case1:
alert(1);
break;
case2:
case3:
alert('2,3');
break;
}
: break , .
, . ,
case, case4, , , break.
case2/case3 case4 .
else?
, .
, '?' '||'
'?':
functioncheckAge(age){
return(age>18)?true:confirm('?');
}
||( ):
functioncheckAge(age){
return(age>18)||confirm('?');
}
min
if:
functionmin(a,b){
if(a<b){
returna;
}else{
returnb;
}
}
'?':
functionmin(a,b){
returna<b?a:b;
}
P.S. a==b , ,
.
pow(x,n)
/**
*xn(JSDoc)
*
*@param{number}x,
*@param{number}n,1
*
*@return{number}xn
*/
functionpow(x,n){
varresult=x;
for(vari=1;i<n;i++){
result*=x;
}
returnresult;
}
varx=prompt("x?",'');
varn=prompt("n?",'');
if(n<=1){
alert(''+n+
',,1'
);
}else{
alert(pow(x,n));
}
:
functionsumTo(n){
varsum=0;
for(vari=1;i<=n;i++){
sum+=i;
}
returnsum;
}
alert(sumTo(100));
:
functionsumTo(n){
if(n==1)return1;
returnn+sumTo(n1);
}
alert(sumTo(100));
: sumTo(n)=n*(n+1)/2:
functionsumTo(n){
returnn*(n+1)/2;
}
alert(sumTo(100));
P.S. , ? .
n, n
.
. ,
,
.
.
P.P.S. ,
sumTo(100000) .
, , n! n*(n1)!.
, n n,
n1, 1!:
functionfactorial(n){
return(n!=1)?n*factorial(n1):1;
}
alert(factorial(5));//120
1. 0.
:
functionfactorial(n){
returnn?n*factorial(n1):1;
}
alert(factorial(5));//120
factorial(1) 1*factorial(0),
.
()
, :
functionfib(n){
returnn<=1?n:fib(n1)+fib(n2);
}
alert(fib(3));//2
alert(fib(7));//13
//fib(77);//,
n . , fib(77)
.
, .
. , :
...
fib(5)=fib(4)+fib(3)
fib(4)=fib(3)+fib(2)
...
, a b 2 c:
a=b,b=c;
c=a+b;
/*():
abc
1,1,2,3
*/
:
a=b,b=c;
c=a+b;
/*():
abc
1,1,2,3,5
*/
, . ,
, .
P.S. .
functionfib(n){
vara=1,
b=1;
for(vari=3;i<=n;i++){
varc=a+b;
a=b;
b=c;
}
returnb;
}
alert(fib(3));//2
alert(fib(7));//13
alert(fib(77));//5527939700884757
i=3,
a=1, b=1.
NFE
function..., , IE8-.
//(FunctionDeclaration)
functiong(){return1;};
alert(g);//
, FunctionDeclaration,
, NamedFunctionExpression. ,
g .
//NamedFunctionExpression!
(functiong(){return1;});
alert(g);//!
, IE8-, ,
"undefinedvariable".
, -:
functionpow(x,n)//<
{//<
varresult=1;//<=
for(vari=0;i<n;i++){result*=x;}//<
//{...}
returnresult;
}
x=prompt("x?",'')//<,,;
n=prompt("n?",'')
if(n<0)//<,
{//<
//,
alert(''+n+',,0');
}
else//<}else{
{
alert(pow(x,n))//
}
:
functionpow(x,n){
varresult=1;
for(vari=0;i<n;i++){
result*=x;
}
returnresult;
}
varx=prompt("x?","");
varn=prompt("n?","");
if(n<0){
alert(''+n+
',,0');
}else{
alert(pow(x,n));
}
chai mocha
pow
functionpow(x,n){
if(n<0)returnNaN;
if(Math.round(n)!=n)returnNaN;
varresult=1;
for(vari=0;i<n;i++){
result*=x;
}
returnresult;
}
, , :
it("01",function(){
assert.equal(pow(123,0),1);
});
, .
describe, ,
:
describe(",,01",function(){
functionmakeTest(x){
it(""+x+"0:1",function(){
assert.equal(pow(x,0),1);
});
}
for(varx=5;x<=5;x+=2){
makeTest(x);
}
});
:
...
it("NaN",function(){
assert(isNaN(pow(0,0),"00NaN");
});
...
?
, .
, ,
, assert.
, ,
.
- ,
, ,
.
it,
.
describe("xn",function(){
it("515",function(){
assert.equal(pow(5,1),5);
});
it("5225",function(){
assert.equal(pow(5,2),25);
});
it("53125",function(){
assert.equal(pow(5,3),125);
});
});
it, ,
. it
, , .
vara=+prompt("","");
varb=+prompt("","");
alert(a+b);
+ prompt,
. , a b ,
"1"+"2"="12".
6.35.toFixed(1) == 6.3?
6.35 .
.. , :
alert(6.35.toFixed(20));//6.34999999999999964473
6.34..., .
.
1. ( ..).
.
100.
2. ,
2 . , :
varprice1=0.1,price2=0.2;
alert(+(price1+price2).toFixed(2));
i 10.
, i:
vari=0;
while(i<11){
i+=0.2;
if(i>9.8&&i<10.2)alert(i);
}
10.
:
functiongetDecimal(num){
returnnumMath.floor(num);
}
alert(getDecimal(12.5));//0.5
alert(getDecimal(1.2));//0.8,!
, .
, Math.floor ,
Math.floor(1.2)=2, , .. 1.
:
functiongetDecimal(num){
returnnum>0?numMath.floor(num):Math.ceil(num)num;
}
alert(getDecimal(12.5));//0.5
alert(getDecimal(1.2));//0.19999999999999996,!
alert(getDecimal(1.2));//0.19999999999999996
, , , .
,
.
1.
:
functiongetDecimal(num){
returnnum>0?(num%1):(num%1);
}
alert(getDecimal(12.5));//0.5
alert(getDecimal(1.2));//0.19999999999999996,!
-, , , , , .
?
, .
.
, .
, .
, , ,
2 , +num.toFixed(2).
, :
functiongetDecimal(num){
varstr=""+num;
varzeroPos=str.indexOf(".");
if(zeroPos==1)return0;
str=str.slice(zeroPos);
return+str;
}
alert(getDecimal(12.5));//0.5
alert(getDecimal(1.2));//0.2
functionfibBinet(n){
varphi=(1+Math.sqrt(5))/2;
//Math.round
returnMath.round(Math.pow(phi,n)/Math.sqrt(5));
}
functionfib(n){
vara=1,
b=0,
x;
for(i=0;i<n;i++){
x=a+b;
a=b
b=x;
}
returnb;
}
alert(fibBinet(2));//1,fib(2)
alert(fibBinet(8));//21,fib(8)
alert(fibBinet(77));//5527939700884755
alert(fib(77));//5527939700884757,!
F77 !
, 5 .
, , .
(0, max)
0..1 max:
varmax=10;
alert(Math.random()*max);
(min, max)
0..maxmin, min:
varmin=5,
max=10;
alert(min+Math.random()*(maxmin));
min max
(round)
, min..max
Math.round, :
functionrandomInteger(min,max){
varrand=min+Math.random()*(maxmin)
rand=Math.round(rand);
returnrand;
}
alert(randomInteger(1,3));
. :
min max , .
, 2 .
- , Math.round()
1 3, , :
1...1.49999..1
1.5...2.49999..2
2.5...2.99999..3
, 1( 3) ,
2. - .
round
: Math.round(min0.5max+0.5)
functionrandomInteger(min,max){
varrand=min0.5+Math.random()*(maxmin+1)
rand=Math.round(rand);
returnrand;
}
alert(randomInteger(5,10));
(maxmin+1), round.
floor
Math.floor() min
max+1.
, 1 3,
1 4( 4).
Math.floor() :
1...1.999+1
2...2.999+2
3...3.999+3
. , :
functionrandomInteger(min,max){
varrand=min+Math.random()*(max+1min);
rand=Math.floor(rand);
returnrand;
}
alert(randomInteger(5,10));
, .. JavaScript .
, :
varnewStr=str[0].toUpperCase()+str.slice(1);
, , , .
str[0]==undefined, undefined toUpperCase().
. str.charAt(0), ,
, undefined. ,
:
functionucFirst(str){
//false
if(!str)returnstr;
returnstr[0].toUpperCase()+str.slice(1);
}
alert(ucFirst(""));
P.S. , ,
.
.
indexOf . , 'xXx'
'XXX'.
str .
functioncheckSpam(str){
varlowerStr=str.toLowerCase();
return!!(~lowerStr.indexOf('viagra')||~lowerStr.indexOf('xxx'));
}
alert(checkSpam('buyViAgRAnow'));
alert(checkSpam('freexxxxx'));
alert(checkSpam("innocentrabbit"));
maxlength,
, .
functiontruncate(str,maxlength){
if(str.length>maxlength){
returnstr.slice(0,maxlength3)+'...';
//maxlength
}
returnstr;
}
alert(truncate(",:",20));
alert(truncate("!",20));
:
functiontruncate(str,maxlength){
return(str.length>maxlength)?
str.slice(0,maxlength3)+'...':str;
}
: +str.slice(1).
.
varuser={};
user.name="";
user.surname="";
user.name="";
deleteuser.name;
,
functionisEmpty(obj){
for(varkeyinobj){
returnfalse;
}
returntrue;
}
varschedule={};
alert(isEmpty(schedule));//true
schedule["8:30"]="";
alert(isEmpty(schedule));//false
"usestrict";
varsalaries={
"":100,
"":300,
"":250
};
varsum=0;
for(varnameinsalaries){
sum+=salaries[name];
}
alert(sum);
"usestrict";
varsalaries={
"":100,
"":300,
"":250
};
varmax=0;
varmaxName="";
for(varnameinsalaries){
if(max<salaries[name]){
max=salaries[name];
maxName=name;
}
}
alert(maxName||"");
2
varmenu={
width:200,
height:300,
title:"Mymenu"
};
functionisNumeric(n){
return!isNaN(parseFloat(n))&&isFinite(n);
}
functionmultiplyNumeric(obj){
for(varkeyinobj){
if(isNumeric(obj[key])){
obj[key]*=2;
}
}
}
multiplyNumeric(menu);
alert("menuwidth="+menu.width+"height="+menu.height+"title="+menu.title);
1, .
:
varfruits=["","",""];
fruits.length 3. 0,
1, 2.
, goods:
varlastItem=goods[goods.length1];//
goods.length1. ,
goods.length:
goods[goods.length]=''
varstyles=["",""];
styles.push("");
styles[styles.length2]="";
alert(styles.shift());
styles.unshift("","");
0 arr.length1.
vararr=["","","",""];
varrand=Math.floor(Math.random()*arr.length);
alert(arr[rand]);
: value prompt,
value=+value,
. , .
varnumbers=[];
while(true){
varvalue=prompt("",0);
if(value===""||value===null||isNaN(value))break;
numbers.push(+value);
}
varsum=0;
for(vari=0;i<numbers.length;i++){
sum+=numbers[i];
}
alert(sum);
?
vararr=[1,2,3];
vararr2=arr;//(*)
arr2[0]=5;
alert(arr[0]);
alert(arr2[0]);
5 , . (*)
arr2 , - ,
, arr2 arr.
, arr2==arr true.
, , , :
vararr2=[];
for(vari=0;i<arr.length;i++)arr2[i]=arr[i];
:
functionfind(array,value){
for(vari=0;i<array.length;i++){
if(array[i]==value)returni;
}
return1;
}
, , .. == 0 false.
===. , JavaScript
Array#indexOf , .
, .
functionfind(array,value){
if(array.indexOf){//
returnarray.indexOf(value);
}
for(vari=0;i<array.length;i++){
if(array[i]===value)returni;
}
return1;
}
vararr=["a",1,2,"b"];
varindex=find(arr,2);
alert(index);
find-
indexOf:
//indexOf
if([].indexOf){
varfind=function(array,value){
returnarray.indexOf(value);
}
}else{
varfind=function(array,value){
for(vari=0;i<array.length;i++){
if(array[i]===value)returni;
}
return1;
}
}
, .. find
indexOf.
.
1. varresults=[].
2. arr .
3. results.
functionfilterRange(arr,a,b){
varresult=[];
for(vari=0;i<arr.length;i++){
if(arr[i]>=a&&arr[i]<=b){
result.push(arr[i]);
}
}
returnresult;
}
vararr=[5,4,3,8,0];
varfiltered=filterRange(arr,3,5);
alert(filtered);
1060.
//1
vararr=[];
for(vari=2;i<100;i++){
arr[i]=true
}
//2
varp=2;
do{
//3
for(i=2*p;i<100;i+=p){
arr[i]=false;
}
//4
for(i=p+1;i<100;i++){
if(arr[i])break;
}
p=i;
}while(p*p<100);//5
//6()
//
varsum=0;
for(i=0;i<arr.length;i++){
if(arr[i]){
sum+=i;
}
}
alert(sum);
( )
,
.
, [1,2,3,9,11]:
//1:
1
1+2
1+2+3
1+2+3+(9)
1+2+3+(9)+11
//2:
2
2+3
2+3+(9)
2+3+(9)+11
//3:
3
3+(9)
3+(9)+11
//9
9
9+11
//11
11
, ,
, .
:
functiongetMaxSubSum(arr){
varmaxSum=0;//,0
for(vari=0;i<arr.length;i++){
varsumFixedStart=0;
for(varj=i;j<arr.length;j++){
sumFixedStart+=arr[j];
maxSum=Math.max(maxSum,sumFixedStart);
}
}
returnmaxSum;
}
alert(getMaxSubSum([1,2,3,9]));//5
alert(getMaxSubSum([1,2,3,9,11]));//11
alert(getMaxSubSum([2,1,1,2]));//3
alert(getMaxSubSum([1,2,3]));//6
alert(getMaxSubSum([100,9,2,3,5]));//100
O(n2), 2
4 . (1000, 10000
) .
( )
s .
- s , s=0.
, s, ,
.
.
, , s .
, , ,
, ,
.
,
: .
functiongetMaxSubSum(arr){
varmaxSum=0,
partialSum=0;
for(vari=0;i<arr.length;i++){
partialSum+=arr[i];
maxSum=Math.max(maxSum,partialSum);
if(partialSum<0)partialSum=0;
}
returnmaxSum;
}
alert(getMaxSubSum([1,2,3,9]));//5
alert(getMaxSubSum([1,2,3,9,11]));//11
alert(getMaxSubSum([2,1,1,2]));//3
alert(getMaxSubSum([100,9,2,3,5]));//100
alert(getMaxSubSum([1,2,3]));//6
alert(getMaxSubSum([1,2,3]));//0
, O(n).
.
obj.className split.
, .
functionaddClass(obj,cls){
varclasses=obj.className?obj.className.split(''):[];
for(vari=0;i<classes.length;i++){
if(classes[i]==cls)return;//
}
classes.push(cls);//
obj.className=classes.join('');//
}
varobj={
className:'openmenu'
};
addClass(obj,'new');
addClass(obj,'open');
addClass(obj,'me');
alert(obj.className)//openmenunewme
P.S.
obj.className.indexOf(cls) . , cls="menu"
obj.className="openmymenu".
P.P.S. , obj.className+=""+cls.
, obj.className=""?
.
border-left-width borderLeftWidth
.
str.split(''), .
, :
functioncamelize(str){
vararr=str.split('');
for(vari=1;i<arr.length;i++){
//:
arr[i]=arr[i].charAt(0).toUpperCase()+arr[i].slice(1);
}
returnarr.join('');
}
alert(camelize("backgroundcolor"));//backgroundColor
alert(camelize("liststyleimage"));//listStyleImage
alert(camelize("webkittransition"));//WebkitTransition
removeClass
, className ,
. splice,
.
functionremoveClass(obj,cls){
varclasses=obj.className.split('');
for(i=0;i<classes.length;i++){
if(classes[i]==cls){
classes.splice(i,1);//
i;//(*)
}
}
obj.className=classes.join('');
}
varobj={
className:'openmenumenu'
}
removeClass(obj,'blabla');
removeClass(obj,'menu')
alert(obj.className)//open
. .
splice , i, , ,
.
, i , .
, (*) i,
i. .
functionfilterRangeInPlace(arr,a,b){
for(vari=0;i<arr.length;i++){
varval=arr[i];
if(val<a||val>b){
arr.splice(i,1);
}
}
}
vararr=[5,3,8,1];
filterRangeInPlace(arr,1,4);
alert(arr);//[3,1]
vararr=[5,2,1,10,8];
functioncompareReversed(a,b){
returnba;
}
arr.sort(compareReversed);
alert(arr);
slice(), :
vararr=["HTML","JavaScript","CSS"];
vararrSorted=arr.slice().sort();
alert(arrSorted);
alert(arr);
.
Math.random.
Math.random() 0 1. 0.5,
[0.5...0.5).
vararr=[1,2,3,4,5];
functioncompareRandom(a,b){
returnMath.random()0.5;
}
arr.sort(compareRandom);
alert(arr);//,[3,5,1,2,4]
sort ,
age:
//
functioncompareAge(personA,personB){
returnpersonA.agepersonB.age;
}
//
varvasya={name:"",age:23};
varmasha={name:"",age:18};
varvovochka={name:"",age:6};
varpeople=[vasya,masha,vovochka];
people.sort(compareAge);
//
for(vari=0;i<people.length;i++){
alert(people[i].name);//
}
varlist={
value:1,
next:{
value:2,
next:{
value:3,
next:{
value:4,
next:null
}
}
}
};
functionprintList(list){
vartmp=list;
while(tmp){
alert(tmp.value);
tmp=tmp.next;
}
}
printList(list);
, tmp,
list. , :
functionprintList(list){
h
i
l
e
(
l
i
s
t
){
w
alert(list.value);
list=list.next;
}
}
-
, .
, ,
, , tmp , i for.
printList(list) :
(1), (2):
varlist={
value:1,
next:{
value:2,
next:{
value:3,
next:{
value:4,
next:null
}
}
}
};
functionprintList(list){
alert(list.value);//(1)
if(list.next){
printList(list.next);//(2)
}
}
printList(list);
, ,
, :
varlist={
value:1,
next:{
value:2,
next:{
value:3,
next:{
value:4,
next:null
}
}
}
};
functionprintReverseList(list){
if(list.next){
printReverseList(list.next);
}
alert(list.value);
}
printReverseList(list);
varlist={
value:1,
next:{
value:2,
next:{
value:3,
next:{
value:4,
next:null
}
}
}
};
functionprintReverseList(list){
vararr=[];
vartmp=list;
while(tmp){
arr.push(tmp.value);
tmp=tmp.next;
}
for(vari=arr.length1;i>=0;i){
alert(arr[i]);
}
}
printReverseList(list);
.
, :
, .
,
( ): ,
. ,
.
, ,
, .
. ,
, .
, , ,
.
, .
.
:
,>
,>
...
.
,
:
functionaclean(arr){
//
varobj={};
for(vari=0;i<arr.length;i++){
//,
varsorted=arr[i].toLowerCase().split('').sort().join('');//(*)
obj[sorted]=arr[i];//
}
varresult=[];
//obj
for(varkeyinobj)result.push(obj[key]);
returnresult;
}
vararr=["","","","","","",""];
alert(aclean(arr));
(*).
(JavaScript ):
varsorted=arr[i]//
.toLowerCase()//
.split('')//['','','']
.sort()//['','','']
.join('');//
, '' ''
''.
:
obj[sorted]=arr[i];
obj obj['']="",
obj['']=''.
, , ,
.
,
.
.
()
.
, . :
functionunique(arr){
varresult=[];
nextInput:
for(vari=0;i<arr.length;i++){
varstr=arr[i];//
for(varj=0;j<result.length;j++){//,?
if(result[j]==str)continuenextInput;//,
}
result.push(str);
}
returnresult;
}
varstrings=["","","","",
"","","","","8()"
];
alert(unique(strings));//,,8()
, .
, 100. , result
. .
, ?
,
.
1. 0 result(
).
2. 1 result.
3. 2 result.
4. n- n1 result.
0+1+2+...+n1=(n1)*n/2=n2/2n/2(
), n.
. 100 4950, 1000 499500(
).
. for
arr.indexOf, , indexOf
.
()
obj. , ,
. .
, "" (obj[""]=true),
.
obj={} .
for..in. .
functionunique(arr){
varobj={};
for(vari=0;i<arr.length;i++){
varstr=arr[i];
obj[str]=true;//
}
returnObject.keys(obj);//IE8
}
varstrings=["","","","",
"","","","","8()"
];
alert(unique(strings));//,,8()
, .
.
map
vararr=["","","",""];
vararrLength=arr.map(function(item){
returnitem.length;
});
alert(arrLength);//4,5,2,5
arr.reduce . , , ,
.
:
functiongetSums(arr){
varresult=[];
if(!arr.length)returnresult;
arr.reduce(function(sum,item){
result.push(sum);
returnsum+item;
});
returnresult;
}
l
e
r
t
(
g
e
t
S
u
m
s
(
[
1
,
2
,
3
,
4
,
5
]
)
)
;
/
/
:
1
,
3
,
6
,
1
0
, , . , ?
, , .
, .
- , reduce,
,
result.
:
functiongetSums(arr){
varresult=[];
v
a
r
t
o
t
a
l
S
u
m=arr.reduce(function(sum,item){
result.push(sum);
returnsum+item;
});
e
s
u
l
t
.
p
u
s
h
(
t
o
t
a
l
S
u
m
)
;
r
returnresult;
}
l
e
r
t
(
g
e
t
S
u
m
s
(
[
1
,
2
,
3
,
4
,
5
]
)
)
;
/
/
1
,
3
,
6
,
1
0
,
1
5
a
l
e
r
t
(
g
e
t
S
u
m
s
(
[
2
,
1
,
0
,
1
]
)
)
;
/
/
2
,
3
,
3
,
arguments
-undefined
arguments.length:
functionf(x){
alert(arguments.length?1:0);
}
f(undefined);
f();
functionsum(){
varresult=0;
for(vari=0;i<arguments.length;i++){
result+=arguments[i];
}
returnresult;
}
alert(sum());//0
alert(sum(1));//1
alert(sum(1,2));//3
alert(sum(1,2,3));//6
alert(sum(1,2,3,4));//10
newDate.
, 1.
:
vard=newDate(2012,1,20,3,12);
alert(d);
getDay() , .
, :
functiongetWeekDay(date){
vardays=['','','','','','',''];
returndays[date.getDay()];
}
vardate=newDate(2014,0,3);//32014
alert(getWeekDay(date));//''
toLocaleString:
vardate=newDate(2014,0,3);//32014
alert(date.toLocaleString('ru',{weekday:'short'}));//''
getDay.
, 0 7:
functiongetLocalDay(date){
varday=date.getDay();
if(day==0){//07
day=7;
}
returnday;
}
alert(getLocalDay(newDate(2012,0,3)));//2
, , day
1, 0 () 6().
.
date . :
functiongetDateAgo(date,days){
date.setDate(date.getDate()days);
returndate.getDate();
}
, .
, .
, :
functiongetDateAgo(date,days){
vardateCopy=newDate(date);
dateCopy.setDate(date.getDate()days);
returndateCopy.getDate();
}
vardate=newDate(2015,0,2);
alert(getDateAgo(date,1));//1,(12015)
alert(getDateAgo(date,2));//31,(312014)
alert(getDateAgo(date,365));//2,(22014)
?
, , (.. ):
functiongetLastDayOfMonth(year,month){
vardate=newDate(year,month+1,0);
returndate.getDate();
}
alert(getLastDayOfMonth(2012,0));//31
alert(getLastDayOfMonth(2012,1));//29
alert(getLastDayOfMonth(2013,1));//28
?
Date, , ..
00 00 00 , .
,
1000, :
functiongetSecondsToday(){
varnow=newDate();
//,
vartoday=newDate(now.getFullYear(),now.getMonth(),now.getDate());
vardiff=nowtoday;//
returnMath.round(diff/1000);//
}
alert(getSecondsToday());
//
:
functiongetSecondsToday(){
vard=newDate();
returnd.getHours()*3600+d.getMinutes()*60+d.getSeconds();
};
?
00 00 00
.
1 :
functiongetSecondsToTomorrow(){
varnow=newDate();
//,
a
r
t
o
m
o
r
r
o
w
=
n
e
w
D
a
t
e
(
n
o
w
.
g
e
t
F
u
l
l
Y
e
a
r
(
)
,
n
o
w
.
g
e
t
M
o
n
t
h
(
)
,
n
o
w
.
g
e
t
D
a
t
e
(
)
+
1
);
v
vardiff=tomorrownow;//
returnMath.round(diff/1000);//
}
..
.
1. date.getDate(). :
vardd=date.getDate();
if(dd<10)dd='0'+dd;
2. date.getMonth() , . 1:
varmm=date.getMonth()+1;//112
if(mm<10)mm='0'+mm;
3. date.getFullYear() 4- .
'%':
varyy=date.getFullYear()%100;
if(yy<10)yy='0'+yy;
, , , ,
yy==0(, 2000 ). 0+'0'==
'00', .
:
functionformatDate(date){
vardd=date.getDate();
if(dd<10)dd='0'+dd;
varmm=date.getMonth()+1;
if(mm<10)mm='0'+mm;
varyy=date.getFullYear()%100;
if(yy<10)yy='0'+yy;
returndd+'.'+mm+'.'+yy;
}
vard=newDate(2014,0,30);//302014
alert(formatDate(d));//'30.01.14'
, date .
functionformatDate(date){
vardiff=newDate()date;//
if(diff<1000){//1
return'';
}
varsec=Math.floor(diff/1000);//diff
if(sec<60){
returnsec+'.';
}
varmin=Math.floor(diff/60000);//diff
if(min<60){
returnmin+'.';
}
//,,0
vard=date;
d=[
'0'+d.getDate(),
'0'+(d.getMonth()+1),
''+d.getFullYear(),
'0'+d.getHours(),
'0'+d.getMinutes()
];
for(vari=0;i<d.length;i++){
d[i]=d[i].slice(2);
}
returnd.slice(0,3).join('.')+''+d.slice(3).join(':');
}
alert(formatDate(newDate(newDate1)));//
alert(formatDate(newDate(newDate30*1000)));//30.
alert(formatDate(newDate(newDate5*60*1000)));//5.
alert(formatDate(newDate(newDate86400*1000)));//"..:"
Window
: 1.
if("a"inwindow){
vara=1;
}
alert(a);
, .
, vara window.a:
//window={a:undefined}
if("a"inwindow){//ifwindow.a
vara=1;//
}
alert(a);
a 1.
Window 2
: .
a, "a"inwindow .
.
if("a"inwindow){
a=1;
}
alert(a);//<error!
Window 3
: 1.
a , "a"inwindow
a=1.
if("a"inwindow){
a=1;
}
vara;
alert(a);//1
say ?
, ",undefined".
say('');//??
varphrase='';
functionsay(name){
alert(name+","+phrase);
}
,
undefined.
?
true, .. var
.
, value=true , alert
true.
.
P.S. var, .
window .
var true, .
var window
undefined, 5.
functiontest(){
alert(window);
varwindow=5;
alert(window);
}
test();
, window ,
.
varwindow
, .. LexicalEnvironment.window:
LexicalEnvironment={
window:undefined
}
alert,
, undefined.
, alert 5.
. :
vara=5
(function(){
alert(a)
})()
, vara=5 .
JavaScript :
vara=5(function(){
alert(a)
})()
, 5, .
, :
vara=5;
(function(){
alert(a)
})()
, ,
.
, .
.
1,2,3,4.
currentCount
: window.
, .
varcurrentCount=1;
functionmakeCounter(){
returnfunction(){
returncurrentCount++;
};
}
varcounter=makeCounter();
varcounter2=makeCounter();
alert(counter());//?
alert(counter());//?
alert(counter2());//?
alert(counter2());//?
.
a a b. :
functionsum(a){
returnfunction(b){
returna+b;//aLexicalEnvironment
};
}
alert(sum(1)(2));
alert(sum(5)(1));
,
makeBuffer:
functionmakeBuffer(){
vartext='';
returnfunction(piece){
if(arguments.length==0){//
returntext;
}
text+=piece;
};
};
varbuffer=makeBuffer();
//
buffer('');
buffer('');
buffer('!');
alert(buffer());//'!'
varbuffer2=makeBuffer();
buffer2(0);
buffer2(1);
buffer2(0);
alert(buffer2());//'010'
text='' . text+=piece
piece , ,
.
.
functionmakeBuffer(){
vartext='';
functionbuffer(piece){
if(arguments.length==0){//
returntext;
}
text+=piece;
};
buffer.clear=function(){
text="";
}
returnbuffer;
};
varbuffer=makeBuffer();
buffer("");
buffer("");
alert(buffer());//
buffer.clear();
alert(buffer());//""
varusers=[{
name:"",
surname:'',
age:20
},{
name:"",
surname:'',
age:25
},{
name:"",
surname:'',
age:18
}];
functionbyField(field){
returnfunction(a,b){
returna[field]>b[field]?1:1;
}
}
users.sort(byField('name'));
users.forEach(function(user){
alert(user.name);
});
users.sort(byField('age'));
users.forEach(function(user){
alert(user.name);
});
functionfilter(arr,func){
varresult=[];
for(vari=0;i<arr.length;i++){
varval=arr[i];
if(func(val)){
result.push(val);
}
}
returnresult;
}
vararr=[1,2,3,4,5,6,7];
alert(filter(arr,function(a){
returna%2==0;
}));//2,4,6
inBetween
functionfilter(arr,func){
varresult=[];
for(vari=0;i<arr.length;i++){
varval=arr[i];
if(func(val)){
result.push(val);
}
}
returnresult;
}
functioninBetween(a,b){
returnfunction(x){
returnx>=a&&x<=b;
};
}
vararr=[1,2,3,4,5,6,7];
alert(filter(arr,inBetween(3,6)));//3,4,5,6
inArray
functionfilter(arr,func){
varresult=[];
for(vari=0;i<arr.length;i++){
varval=arr[i];
if(func(val)){
result.push(val);
}
}
returnresult;
}
functioninArray(arr){
returnfunction(x){
returnarr.indexOf(x)!=1;
};
}
vararr=[1,2,3,4,5,6,7];
alert(filter(arr,inArray([1,2,10])));//1,2
makeArmy :
1. shooter:
varshooters=[];
2. shooter.push.
, :
shooters=[
function(){alert(i);},
function(){alert(i);},
function(){alert(i);},
function(){alert(i);},
function(){alert(i);},
function(){alert(i);},
function(){alert(i);},
function(){alert(i);},
function(){alert(i);},
function(){alert(i);}
];
.
3. army[5]() ( ),
.
, .
- shooter i. ,
i LexicalEnvironment.
i?
army[0](), makeArmy . ,
i=10.
shooter ,
, , i=10.
.
(3 )
.
1.
-:
functionmakeArmy(){
varshooters=[];
for(vari=0;i<10;i++){
varshooter=functionme(){
alert(me.i);
};
shooter.i=i;
shooters.push(shooter);
}
returnshooters;
}
vararmy=makeArmy();
army[0]();//0
army[1]();//1
.
, Named Function Expression,
:
...
varshooter=functionme(){
alert(me.i);
};
...
me shooter, :
for(vari=0;i<10;i++){
varshooter=function(){
alert(shooter.i);//(!)
//shooter?
//..,,
};
shooter.i=i;
shooters.push(shooter);
}
alert(shooter.i) shooter,
, ,
.
Named Function Expression,
, me.i i.
2. , ---
, i:
functionmakeArmy(){
varshooters=[];
for(vari=0;i<10;i++){
varshooter=(function(x){
returnfunction(){
alert(x);
};
})(i);
shooters.push(shooter);
}
returnshooters;
}
vararmy=makeArmy();
army[0]();//0
army[1]();//1
, , :
varshooter=(function(x){
returnfunction(){
alert(x);
};
})(i);
shooter
function(x), , x=i.
function(x) , x .
-.
x i,
:
varshooter=(function(i){
returnfunction(){
alert(i);
};
})(i);
, function(i) , :
a
r
s
h
o
o
t
e
r
=
f
u
n
c
t
i
o
n
(
i
)
{
/
/
f
u
n
c
t
i
o
n
(
i
)
v
returnfunction(){
alert(i);
};
}(i);
, ,
, , varshooter=function, ,
.
3. :
functionmakeArmy(){
varshooters=[];
for(vari=0;i<10;i++)(function(i){
varshooter=function(){
alert(i);
};
shooters.push(shooter);
})(i);
returnshooters;
}
vararmy=makeArmy();
army[0]();//0
army[1]();//1
(function(i){...}) , ,
FunctionExpression.
. ,
shooter, .
.
with
With +
(2), .. with
.
, 2:
functionf(){
alert(1)
}
varobj={
f:function(){
alert(2)
}
};
with(obj){
f();
}
With +
3.
with , .
varb , .
:
vara=1;
varb;
varobj={
b:2
}
with(obj){
alert(a+b);
}
, this
arr[2]() obj[method](), obj
arr, : 2.
, , arr[2] this=
arr :
vararr=["a","b"];
arr.push(function(){
alert(this);
})
arr[2]();//"a","b",function
!
:
varobj={
go:function(){
alert(this)
}
}
(obj.go)()//error!
,
.
- , obj .
JavaScript (obj.go)() :
varobj={go:...}(obj.go)()
, {
go:...} (obj.go). , , .
this ?
1. .
2. , .
3. obj.method(), ().method().
, :
f=obj.go;//
f();//,
f() , this.
4. , .
Reference
Type .
obj.go() :
1. obj.go.
2. .
2 this? obj.go
ReferenceType, go
obj. , , ()
this.
, , ReferenceType ,
go( ).
, (method=obj.go) method go,
obj.
(4): || ReferenceType
.
this
: .
varname="";
varuser={
name:"",
export:this//(*)
};
alert(user.export.name);
this. ,
, .
this
: .
user.export() this, ,
user.export() returnthis user.
name user, "".
this
: .
user.export() this=user.
{value:this}, value
, user.
user.export().value==user.
varname="";
varuser={
name:"",
export:function(){
return{
value:this
};
}
};
alert(user.export().value==user);//true
varcalculator={
sum:function(){
returnthis.a+this.b;
},
mul:function(){
returnthis.a*this.b;
},
read:function(){
this.a=+prompt('a?',0);
this.b=+prompt('b?',0);
}
}
calculator.read();
alert(calculator.sum());
alert(calculator.mul());
, .
returnthis :
varladder={
step:0,
up:function(){
this.step++;
returnthis;
},
down:function(){
this.step;
returnthis;
},
showStep:function(){
alert(this.step);
returnthis;
}
}
ladder.up().up().down().up().down().showStep();//1
: toString valueOf
['x'] == 'x'
, , .
. valueOf,
toString, .
, . ['x'] 'x'.
'x'=='x', .
P.S. :
alert(['x','y']=='x,y');//true
alert([]=='');//true
alert(foo)
, toString, .. "foo".
alert(foo + 1)
'+' , valueOf, : 3.
alert(foo + '3')
, , 2.
2+'3'. '+' -
, ,
"23".
[] == [] , [ ] == ![ ] ?
, .
, , .
1. , . ![].
'!' . ,
true. , ![]=!true=false. :
alert([]==false);
2.
.
valueOf, toString ,
:
alert(''==false);
3. :
alert(0==0);
,
newDate(0)0=0//(1)
newArray(1)[0]+""="undefined"//(2)
({})[0]
=undefined//(3)
[1]+1="11"//(4)
[1,2]+[3,4]="1,23,4"//(5)
[]+null+1="null1"//(6)
[[0]][0][0]=0//(7)
({}+{})="[objectObject][objectObject]"//(8)
1. newDate(0) , 0 1
1970 00:00:00 UTC.
, 0.
2. newArray(num) -
, . undefined,
"undefined".
3. , '0'.
undefined. , .
{}[0] 0, .. {}
, .
4. "1". "+"
"1"+"1"="11".
5. .
6. ""+null+1, "+",
null , "null"+1, "null1".
7. [[0]] [0] [].
, .
, :
alert([1,[0],2][1]);
/ ,
.
8. . Object
valueOf, toString,
.
, sum, .
, currentSum.
:
functionsum(a){
varcurrentSum=a;
functionf(b){
currentSum+=b;
returnf;
}
f.toString=function(){
returncurrentSum;
};
returnf;
}
alert(sum(1)(2));//3
alert(sum(5)(1)(2));//6
alert(sum(6)(1)(2)(3));//0
alert(sum(0)(1)(2)(3)(4)(5));//15
, sum
. f.
, f currentSum,
, .
f .
:
functionf(b){
currentSum+=b;
returnf();//<
}
, , .
functionf(b){
currentSum+=b;
returnf;//<,
}
f , , .
, toString,
currentSum.
new
, .
. ,
this .
, obj, :
varobj={};
functionA(){returnobj;}
functionB(){returnobj;}
vara=newA;
varb=newB;
alert(a==b);//true
Calculator
functionCalculator(){
this.read=function(){
this.a=+prompt('a?',0);
this.b=+prompt('b?',0);
};
this.sum=function(){
returnthis.a+this.b;
};
this.mul=function(){
returnthis.a*this.b;
};
}
varcalculator=newCalculator();
calculator.read();
alert("="+calculator.sum());
alert("="+calculator.mul());
Accumulator
functionAccumulator(startingValue){
this.value=startingValue;
this.read=function(){
this.value+=+prompt('?',0);
};
}
varaccumulator=newAccumulator(1);
accumulator.read();
accumulator.read();
alert(accumulator.value);
functionCalculator(){
varmethods={
"":function(a,b){
returnab;
},
"+":function(a,b){
returna+b;
}
};
this.calculate=function(str){
varsplit=str.split(''),
a=+split[0],
op=split[1],
b=+split[2]
if(!methods[op]||isNaN(a)||isNaN(b)){
returnNaN;
}
returnmethods[op](+a,+b);
}
this.addMethod=function(name,func){
methods[name]=func;
};
}
varcalc=newCalculator;
calc.addMethod("*",function(a,b){
returna*b;
});
calc.addMethod("/",function(a,b){
returna/b;
});
calc.addMethod("**",function(a,b){
returnMath.pow(a,b);
});
varresult=calc.calculate("2**3");
alert(result);//8
.
.
calculate.
.
.
get/set-
functionUser(fullName){
this.fullName=fullName;
Object.defineProperties(this,{
firstName:{
get:function(){
returnthis.fullName.split('')[0];
},
set:function(newFirstName){
this.fullName=newFirstName+''+this.lastName;
}
},
lastName:{
get:function(){
returnthis.fullName.split('')[1];
},
set:function(newLastName){
this.fullName=this.firstName+''+newLastName;
}
}
});
}
varvasya=newUser("");
//firstName/lastName
alert(vasya.firstName);//
alert(vasya.lastName);//
//lastName
vasya.lastName='';
alert(vasya.fullName);//
( ):
functionArticle(){
this.created=newDate;
Article.count++;//
Article.last=this.created;//
}
Article.count=0;//
//(undefined,..Article.count++NaN)
Article.showStats=function(){
alert(':'+this.count+',:'+this.last);
};
newArticle();
newArticle();
Article.showStats();//:2,:()
newArticle();
Article.showStats();//:3,:()
functionsumArgs(){
//reduce
arguments.reduce=[].reduce;
returnarguments.reduce(function(a,b){
returna+b;
});
}
alert(sumArgs(4,5,6));//15
call , reduce arguments
.
functionsumArgs(){
//reduce
return[].reduce.call(arguments,function(a,b){
returna+b;
});
}
alert(sumArgs(4,5,6));//15
functionsum(){
return[].reduce.call(arguments,function(a,b){
returna+b;
});
}
functionmul(){
return[].reduce.call(arguments,function(a,b){
returna*b;
});
}
functionapplyAll(func){
returnfunc.apply(this,[].slice.call(arguments,1));
}
alert(applyAll(sum,1,2,3));//6
alert(applyAll(mul,2,3,4));//24
alert(applyAll(Math.max,2,2,3));//3
alert(applyAll(Math.min,2,2,3));//2
: bind
- bind
, ? ( ):
1. bind args( 2 )
bindArgs.
2. wrapper.
3. arguments args , concat,
bindArgs().
4. func .
bind
: Hello.
functionf(){
alert(this);
}
varuser={
g:f.bind("Hello")
}
user.g();
user.g(), g this=user.
, g , this .
f
"Hello", .
, .
bind
: "".
functionf(){
alert(this.name);
}
f=f.bind({name:""}).bind({name:""});
f();//
f.bind(....) ,
f f.
bind .
.
, bind :
functionbind(func,context){
returnfunction(){
returnfunc.apply(context,arguments);
};
}
:
functionf(){
alert(this.name);
}
f=bind(f,{name:""});//(1)
f=bind(f,{name:""});//(2)
f();//
, bind, (1), f,
():
functionbind(func,context){
returnfunction(){
//this
returnfunc.apply(context,arguments);
};
}
this, context .
, this.
bind (2),
this, . , this ,
this ? context, ,
bind.
bind
: undefined.
bind - sayHi.
, test.
bind
, ask , -.
bind, ask :
"usestrict";
functionask(question,answer,ok,fail){
varresult=prompt(question,'');
if(result.toLowerCase()==answer.toLowerCase())ok();
elsefail();
}
varuser={
login:'',
password:'12345',
loginOk:function(){
alert(this.login+'');
},
loginFail:function(){
alert(this.login+':');
},
checkPassword:function(){
ask("?",this.password,this.loginOk.bind(this),this.loginFail.bind(this));
}
};
varvasya=user;
user=null;
vasya.checkPassword();
- user.loginOk/loginFail:
varuser={
...
checkPassword:function(){
ask("?",this.password,
function(){user.loginOk();},function(){user.loginFail();});
}
}
user, ,
, , :
varvasya=user;//uservasya
user=null;
vasya.checkPassword();//,user
, , this. checkPassword
, ,
self:
"usestrict";
functionask(question,answer,ok,fail){
varresult=prompt(question,'');
if(result.toLowerCase()==answer.toLowerCase())ok();
elsefail();
}
varuser={
login:'',
password:'12345',
loginOk:function(){
alert(this.login+'');
},
loginFail:function(){
alert(this.login+':');
},
checkPassword:function(){
varself=this;
ask("?",this.password,
function(){
self.loginOk();
},
function(){
self.loginFail();
}
);
}
};
varvasya=user;
user=null;
vasya.checkPassword();
. ,
self.
bind
ask .
"usestrict";
functionask(question,answer,ok,fail){
varresult=prompt(question,'');
if(result.toLowerCase()==answer.toLowerCase())ok();
elsefail();
}
varuser={
login:'',
password:'12345',
loginDone:function(result){
alert(this.login+(result?'':''));
},
checkPassword:function(){
ask("?",this.password,this.loginDone.bind(this,true),this.loginDone.bind(this,
}
};
user.checkPassword();
this (
):
"usestrict";
functionask(question,answer,ok,fail){
varresult=prompt(question,'');
if(result.toLowerCase()==answer.toLowerCase())ok();
elsefail();
}
varuser={
login:'',
password:'12345',
loginDone:function(result){
alert(this.login+(result?'':''));
},
checkPassword:function(){
varself=this;
ask("?",this.password,
function(){
self.loginDone(true);
},
function(){
self.loginDone(false);
}
);
}
};
user.checkPassword();
, bind.
-,
(1 )
wrapper log
f:
functionwork(a){
/*...*///work,
}
functionmakeLogging(f,log){
functionwrapper(a){
log.push(a);
returnf.call(this,a);
}
returnwrapper;
}
varlog=[];
work=makeLogging(work,log);
work(1);//1
work(5);//5
for(vari=0;i<log.length;i++){
alert(':'+log[i]);//":1",":5"
}
, f.call(this,a),
f(a).
, .
:
user.method=makeLogging(user.method,log);
user.method(...) this,
call/apply.
.
( )
(1 ), ,
arguments.
f.apply(this,
arguments).
functionwork(a,b){
alert(a+b);//work
}
functionmakeLogging(f,log){
functionwrapper(){
log.push([].slice.call(arguments));
returnf.apply(this,arguments);
}
returnwrapper;
}
varlog=[];
work=makeLogging(work,log);
work(1,2);//3
work(4,5);//9
for(vari=0;i<log.length;i++){
varargs=log[i];//i
alert(':'+args.join());//":1,2",":4,5"
}
, cache:{
:}.
functionf(x){
returnMath.random()*x;
}
functionmakeCaching(f){
varcache={};
returnfunction(x){
if(!(xincache)){
cache[x]=f.call(this,x);
}
returncache[x];
};
}
f=makeCaching(f);
vara=f(1);
varb=f(1);
alert(a==b);//true()
b=f(2);
alert(a==b);//false,=>
: : if(x
incache). : if(cache[x]),
, cache[x] false, 0 ..
.
: [[Class]], instanceof
formatDate
/ typeof.
:
alert(typeof123);//"number"
alert(typeof"");//"string"
alert(typeofnewDate());//"object"
alert(typeof[]);//"object"
typeof , :
"object". Date Array.
Array Array.isArray. , .
.
JSON, toJSON
JSON
varleader={
name:"",
age:35
};
varleaderStr=JSON.stringify(leader);
leader=JSON.parse(leaderStr);
JSON
JSON.stringify(team) , leader soldier
.
JSON .
JSON, :
1. team toJSON:
team.toJSON=function(){
/*,JSON.s
}
, , JSON,
, .
2. , id.
, , .
:
varleader={
id:12,
name:""
};
varsoldier={
id:51,
name:""
};
//ID
leader.soldierId=51;
soldier.leaderId=12;
varteam={
12:leader,
51:soldier
};
.. ?
, - JSON.
, .
,
JSON,
.
, , Dojo.
dojox.json.ref.toJson(team)
:
[{"name":"","soldier":{"name":"","leader":{"$ref":"#0"}}},{"$ref":"#0.soldier"
: dojox.json.ref.fromJson.
setTimeout setInterval
100
functionprintNumbersInterval(){
vari=1;
vartimerId=setInterval(function(){
console.log(i);
if(i==20)clearInterval(timerId);
i++;
},100);
}
//
printNumbersInterval();
100, setTimeout
functionprintNumbersTimeout20_100(){
vari=1;
vartimerId=setTimeout(functiongo(){
console.log(i);
if(i<20)setTimeout(go,100);
i++;
},100);
}
//
printNumbersTimeout20_100();
setInterval setTimeout?
2,
highlight.
100%, highlight ,
10 , , 10, ..
.
, ,
. 100%
. , , ,
2.
setTimeout?
:
alert 100000000.
3, hardWork.
, 100 setTimeout,
, 100,
.
setInterval?
alert(i) setTimeout 100000001.
:
vartimer=setInterval(function(){
i++;
},10);
setTimeout(function(){
clearInterval(timer);
alert(i);//(*)
},50);
vari;
functionf(){
//
//100
for(i=0;i<1e8;i++)f[i%2]=i;
}
f();
: 3 ( f ).
setInterval 10 .
,
.
f ,
setInterval, , ..
. setInterval.
, setInterval . setTimeout,
.
, , setInterval 1
. -.
?
.
, JavaScript , IE.
, 1.
(Chrome) .
Runner :
functionRunner(){
this.steps=0;
this.step=function(){
this.doSomethingHeavy();
this.steps++;
};
functionfib(n){
returnn<=1?n:fib(n1)+fib(n2);
}
this.doSomethingHeavy=function(){
for(vari=0;i<25;i++){
this[i]=fib(i);
}
};
}
varrunner1=newRunner();
varrunner2=newRunner();
//
vart1=setInterval(function(){
runner1.step();
},15);
vart2=setTimeout(functiongo(){
runner2.step();
t2=setTimeout(go,15);
},15);
//?
setTimeout(function(){
clearInterval(t1);
clearTimeout(t2);
alert(runner1.steps);
alert(runner2.steps);
},5000);
step() doSomethingHeavy(),
, .
, , - , doSomethingHeavy()
, () ,
. setTimeout 15 , setInterval
, 15. .
functiondelay(f,ms){
returnfunction(){
varsavedThis=this;
varsavedArgs=arguments;
setTimeout(function(){
f.apply(savedThis,savedArgs);
},ms);
};
}
functionf(x){
alert(x);
}
varf1000=delay(f,1000);
varf1500=delay(f,1500);
f1000("");//""1000
f1500("2");//"2"1500
, :
returnfunction(){
varsavedThis=this;
varsavedArgs=arguments;
setTimeout(function(){
f.apply(savedThis,savedArgs);
},ms);
};
delay .
, ms,
savedThis savedArgs.
, -
, setTimeout.
.
functiondebounce(f,ms){
varstate=null;
varCOOLDOWN=1;
returnfunction(){
if(state)return;
f.apply(this,arguments);
state=COOLDOWN;
setTimeout(function(){state=null},ms);
}
}
functionf(x){alert(x)}
varf=debounce(f,1000);
f(1);//1,
f(2);//
setTimeout(function(){f(3)},100);//(100)
setTimeout(function(){f(4)},1100);//4,
setTimeout(function(){f(5)},1500);//
debounce -.
.
state COOLDOWN(
).
, .
.
functionthrottle(func,ms){
varisThrottled=false,
savedArgs,
savedThis;
functionwrapper(){
if(isThrottled){//(2)
savedArgs=arguments;
savedThis=this;
return;
}
func.apply(this,arguments);//(1)
isThrottled=true;
setTimeout(function(){
isThrottled=false;//(3)
if(savedArgs){
wrapper.apply(savedThis,savedArgs);
savedArgs=savedThis=null;
}
},ms);
}
returnwrapper;
}
:
1. throttle - wrapper,
func (isThrottled=true).
2.
savedArgs/savedThis. ,
. ,
.
3. , ms , wrapper
( ).
(3) , wrapper,
func, .
.. .. ",
.
.
.
: eval
Eval-
eval:
varexpr=prompt("?",'2*3+2');
alert(eval(expr));
, .
,
, ,
.
, try..catch
Finally ?
, .
, - try..catch.
, finally return:
functionf(){
try{
...
returnresult;
}catch(e){
...
}finally{
}
}
- throw:
functionf(){
try{
...
}catch(e){
...
if(){
throwe;
}
}finally{
}
}
finally f,
.
Eval-
eval:
alert(eval("2+2"));//4
while(true).
try..catch.
, , NaN eval,
. .
:
varexpr,res;
while(true){
expr=prompt("?",'2');
if(expr==null)break;
try{
res=eval(expr);
if(isNaN(res)){
thrownewError("");
}
break;
}catch(e){
alert(":"+e.message+",");
}
}
alert(res);
:
functionCoffeeMachine(power){
this.waterAmount=0;
varWATER_HEAT_CAPACITY=4200;
vartimerId;
varself=this;
functiongetBoilTime(){
returnself.waterAmount*WATER_HEAT_CAPACITY*80/power;
}
functiononReady(){
alert('!');
}
this.run=function(){
timerId=setTimeout(onReady,getBoilTime());
};
this.stop=function(){
clearTimeout(timerId)
};
}
varcoffeeMachine=newCoffeeMachine(50000);
coffeeMachine.waterAmount=200;
coffeeMachine.run();
coffeeMachine.stop();//
functionUser(){
varfirstName,surname;
this.setFirstName=function(newFirstName){
firstName=newFirstName;
};
this.setSurname=function(newSurname){
surname=newSurname;
};
this.getFullName=function(){
returnfirstName+''+surname;
}
}
varuser=newUser();
user.setFirstName("");
user.setSurname("");
alert(user.getFullName());//
, getFullName ,
. . /
,
, , .
power
functionCoffeeMachine(power,capacity){
//...
this.setWaterAmount=function(amount){
if(amount<0){
thrownewError("");
}
if(amount>capacity){
thrownewError(","+capacity);
}
waterAmount=amount;
};
this.getWaterAmount=function(){
returnwaterAmount;
};
this.getPower=function(){
returnpower;
};
}
addWater setWaterAmount.
functionCoffeeMachine(power,capacity){
varwaterAmount=0;
varWATER_HEAT_CAPACITY=4200;
functiongetTimeToBoil(){
returnwaterAmount*WATER_HEAT_CAPACITY*80/power;
}
this.setWaterAmount=function(amount){
if(amount<0){
thrownewError("");
}
if(amount>capacity){
thrownewError(","+capacity);
}
waterAmount=amount;
};
this.addWater=function(amount){
this.setWaterAmount(waterAmount+amount);
};
functiononReady(){
alert('!');
}
this.run=function(){
setTimeout(onReady,getTimeToBoil());
};
}
varcoffeeMachine=newCoffeeMachine(100000,400);
coffeeMachine.addWater(200);
coffeeMachine.addWater(100);
coffeeMachine.addWater(300);//..
coffeeMachine.run();
onReady
functionCoffeeMachine(power,capacity){
varwaterAmount=0;
varWATER_HEAT_CAPACITY=4200;
functiongetTimeToBoil(){
returnwaterAmount*WATER_HEAT_CAPACITY*80/power;
}
this.setWaterAmount=function(amount){
//...
waterAmount=amount;
};
this.getWaterAmount=function(amount){
returnwaterAmount;
};
functiononReady(){
alert('!');
}
this.setOnReady=function(newOnReady){
onReady=newOnReady;
};
this.run=function(){
setTimeout(function(){
onReady();
},getTimeToBoil());
};
}
varcoffeeMachine=newCoffeeMachine(20000,500);
coffeeMachine.setWaterAmount(150);
coffeeMachine.run();
coffeeMachine.setOnReady(function(){
varamount=coffeeMachine.getWaterAmount();
alert(':'+amount+'');//:150
});
:
1. setOnReady newOnReady.
onReady, (
):
//
this.setOnReady=function(onReady){
onReady=onReady;//???onReady
};
2. setOnReady , setTimeout
onReady, function(){onReady()},
( ) onReady .
isRunning
run
timerId, :
functionCoffeeMachine(power,capacity){
varwaterAmount=0;
vartimerId;
this.isRunning=function(){
return!!timerId;
};
varWATER_HEAT_CAPACITY=4200;
functiongetTimeToBoil(){
returnwaterAmount*WATER_HEAT_CAPACITY*80/power;
}
this.setWaterAmount=function(amount){
//...
waterAmount=amount;
};
this.getWaterAmount=function(amount){
returnwaterAmount;
};
functiononReady(){
alert('!');
}
this.setOnReady=function(newOnReady){
onReady=newOnReady;
};
this.run=function(){
timerId=setTimeout(function(){
timerId=null;
onReady();
},getTimeToBoil());
};
}
varcoffeeMachine=newCoffeeMachine(20000,500);
coffeeMachine.setWaterAmount(100);
alert(':'+coffeeMachine.isRunning());//:false
coffeeMachine.run();
alert(':'+coffeeMachine.isRunning());//:true
coffeeMachine.setOnReady(function(){
alert(":"+coffeeMachine.isRunning());//:false
});
run:
this.run=function(){
if(!this._enabled){
thrownewError("");
}
setTimeout(onReady,1000);
};
functionFridge(power){
//
Machine.apply(this,arguments);
varfood=[];//food
this.addFood=function(){
if(!this._enabled){
thrownewError("");
}
if(food.length+arguments.length>=this._power/100){
thrownewError(",");
}
for(vari=0;i<arguments.length;i++){
food.push(arguments[i]);//arguments
}
};
this.getFood=function(){
//,food
returnfood.slice();
};
}
functionMachine(power){
this._power=power;
this._enabled=false;
varself=this;
this.enable=function(){
self._enabled=true;
};
this.disable=function(){
self._enabled=false;
};
}
functionFridge(power){
//
Machine.apply(this,arguments);
varfood=[];//food
this.addFood=function(){
if(!this._enabled){
thrownewError("");
}
if(food.length+arguments.length>=this._power/100){
thrownewError(",");
}
for(vari=0;i<arguments.length;i++){
food.push(arguments[i]);//arguments
}
};
this.getFood=function(){
this.getFood=function(){
//,food
returnfood.slice();
};
this.filterFood=function(filter){
returnfood.filter(filter);
};
this.removeFood=function(item){
varidx=food.indexOf(item);
if(idx!=1)food.splice(idx,1);
};
}
varfridge=newFridge(500);
fridge.enable();
fridge.addFood({
title:"",
calories:100
});
fridge.addFood({
title:"",
calories:30
});
fridge.addFood({
title:"",
calories:10
});
fridge.addFood({
title:"",
calories:150
});
vardietItems=fridge.filterFood(function(item){
returnitem.calories<50;
});
fridge.removeFood("");//
alert(fridge.getFood().length);//4
dietItems.forEach(function(item){
alert(item.title);//,
fridge.removeFood(item);
});
alert(fridge.getFood().length);//2
disable
functionMachine(power){
this._power=power;
this._enabled=false;
varself=this;
this.enable=function(){
self._enabled=true;
};
this.disable=function(){
self._enabled=false;
};
}
functionFridge(power){
Machine.apply(this,arguments);
varfood=[];//food
this.addFood=function(){
if(!this._enabled){
thrownewError("");
}
if(food.length+arguments.length>=this._power/100){
thrownewError(",");
}
for(vari=0;i<arguments.length;i++){
food.push(arguments[i]);//arguments
}
};
this.getFood=function(){
//,food
returnfood.slice();
};
this.filterFood=function(filter){
returnfood.filter(filter);
};
this.removeFood=function(item){
varidx=food.indexOf(item);
if(idx!=1)food.splice(idx,1);
};
varparentDisable=this.disable;
this.disable=function(){
if(food.length){
thrownewError(":");
}
parentDisable();
};
}
varfridge=newFridge(500);
fridge.enable();
fridge.addFood("");
fridge.disable();//,
c delete?
1. true, rabbit.
2. null, animal.
3. undefined, .
this
: rabbit.
this rabbit,
.
rabbit.eat():
1. rabbit.eat, . eat
rabbit, rabbit.__proto__ .
2. eat. , .. this=
rabbit.
, this.full=true full
rabbit. :
, , ,
this, ,
.
1. __proto__:
varhead={
glasses:1
};
vartable={
pen:3
};
table.__proto__=head;
varbed={
sheet:1,
pillow:2
};
bed.__proto__=table;
varpockets={
money:2000
};
pockets.__proto__=bed;
alert(pockets.pen);//3
alert(bed.glasses);//1
alert(table.money);//undefined
2. , , ,
. ,
, , pockets.glasses
(head).
F.prototype new
: true,
: true. prototype __proto__ .
rabbit.__proto__. eats
.
: false. Rabbit.prototype rabbit.__proto__
. .
: true, deleterabbit.eats eats rabbit,
. alert .
: undefined. ,
rabbit.eats .
options / :
functionMenu(options){
options=Object.create(options);
options.width=options.width||300;
alert(options.width);//width
alert(options.height);//height
...
}
options, ,
.
1. .
2. .
3. IE8-, getPrototypeOf
4. , IE10-,
__proto__.
, , , - ,
constructor .
, , :
functionUser(name){
this.name=name;
}
varobj=newUser('');
varobj2=newobj.constructor('');
alert(obj2.name);//()
, User.prototype.constructor==User.
-, , User.prototype constructor,
, :
functionUser(name){
this.name=name;
}
User.prototype={};
varobj=newUser('');
varobj2=newobj.constructor('');
alert(obj2.name);//undefined
JavaScript
defer
Function.prototype.defer=function(ms){
setTimeout(this,ms);
}
functionf(){
alert("");
}
f.defer(1000);//""1
defer
Function.prototype.defer=function(ms){
varf=this;
returnfunction(){
varargs=arguments,
context=this;
setTimeout(function(){
f.apply(context,args);
},ms);
}
}
//
functionf(a,b){
alert(a+b);
}
f.defer(1000)(1,2);//31.
functionCoffeeMachine(power){
//
this._power=power;
this._waterAmount=0;
}
//
CoffeeMachine.prototype.WATER_HEAT_CAPACITY=4200;
CoffeeMachine.prototype._getTimeToBoil=function(){
returnthis._waterAmount*this.WATER_HEAT_CAPACITY*80/this._power;
};
CoffeeMachine.prototype.run=function(){
setTimeout(function(){
alert('!');
},this._getTimeToBoil());
};
CoffeeMachine.prototype.setWaterAmount=function(amount){
this._waterAmount=amount;
};
varcoffeeMachine=newCoffeeMachine(10000);
coffeeMachine.setWaterAmount(50);
coffeeMachine.run();
__proto__
speedy.found(""):
1. found speedy. speedy , .. new
Hamster this.
2. speedy.__proto__(==Hamster.prototype)
found, .
3. this , .. speedy.
4. this.food.push() this.food.
speedy, speedy.__proto__.
5. "" speedy.__proto__.food.
! , JavaScript, food
, -.
, :
this.food=something;
, found .
- .
?
. ,
.
functionHamster(){
this.food=[];
}
Hamster.prototype.found=function(something){
this.food.push(something);
};
speedy=newHamster();
lazy=newHamster();
speedy.found("");
speedy.found("");
alert(speedy.food.length)//2
alert(lazy.food.length)//0(!)
. .
JavaScript
:
Rabbit.prototype=Animal.prototype;
, Rabbit.prototype Animal.prototype
. Rabbit , ,
Animal.
, , :
functionAnimal(name){
this.name=name;
}
Animal.prototype.walk=function(){
alert(""+this.name);
};
functionRabbit(name){
this.name=name;
}
Rabbit.prototype=Animal.prototype;
Rabbit.prototype.walk=function(){
alert("!:"+this.name);
};
varanimal=newAnimal("");
animal.walk();//!
:
Rabbit.prototype=Object.create(Animal.prototype);
, Rabbit.prototype ,
Animal.prototype, ,
.
, walk Animal
.
, , ,
:
//...
//
Rabbit.prototype.walk=function(){
alert(""+this.name);
};
this.walk Animal , ,
.
walk Animal.prototype.walk.
, ,
.
functionClock(options){
this._template=options.template;
}
Clock.prototype._render=functionrender(){
vardate=newDate();
varhours=date.getHours();
if(hours<10)hours='0'+hours;
varmin=date.getMinutes();
if(min<10)min='0'+min;
varsec=date.getSeconds();
if(sec<10)sec='0'+sec;
varoutput=this._template.replace('h',hours).replace('m',min).replace('s',sec);
console.log(output);
};
Clock.prototype.stop=function(){
clearInterval(this._timer);
};
Clock.prototype.start=function(){
this._render();
varself=this;
this._timer=setInterval(function(){
self._render();
},1000);
};
functionExtendedClock(options){
Clock.apply(this,arguments);
this._precision=+options.precision||1000;
}
ExtendedClock.prototype=Object.create(Clock.prototype);
ExtendedClock.prototype.start=function(){
this._render();
varself=this;
this._timer=setInterval(function(){
self._render();
},this._precision);
};
: , AnimatingMenu
.
constructor?
, , false.
constructor prototype ,
. ,
.
rabbit.constructor, :
1. rabbit , .
2. Rabbit.prototype Object.create ,
Animal.prototype. constructor' .
: instanceof
instanceof
, , a B.
instanceof . prototype
__proto__.
a.__proto__==B.prototype, instanceof true.
instanceof , instanceof
.
instanceof?
, .
.
functionAnimal(){}
functionRabbit(){}
Rabbit.prototype=Object.create(Animal.prototype);
varrabbit=newRabbit();
alert(rabbitinstanceofRabbit);//true
alert(rabbitinstanceofAnimal);//true
alert(rabbitinstanceofObject);//true
, Error
SyntaxError
functionFormatError(message){
this.name="FormatError";
this.message=message;
if(Error.captureStackTrace){
Error.captureStackTrace(this,this.constructor);
}else{
this.stack=(newError()).stack;
}
}
FormatError.prototype=Object.create(SyntaxError.prototype);
FormatError.prototype.constructor=FormatError;
//
varerr=newFormatError("");
alert(err.message);//
alert(err.name);//FormatError
alert(err.stack);//
alert(errinstanceofSyntaxError);//true