-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.html
1192 lines (1081 loc) · 40.7 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Such Java, Much Script!</title>
<meta name="description" content="A framework for easily creating beautiful presentations using HTML">
<meta name="author" content="Hakim El Hattab">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link rel="stylesheet" href="css/reveal.min.css">
<link rel="stylesheet" href="css/theme/default.css" id="theme">
<!-- For syntax highlighting -->
<link rel="stylesheet" href="lib/css/zenburn.css">
<!-- If the query includes 'print-pdf', include the PDF print sheet -->
<script>
if( window.location.search.match( /print-pdf/gi ) ) {
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'css/print/pdf.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
}
</script>
<!--[if lt IE 9]>
<script src="lib/js/html5shiv.js"></script>
<![endif]-->
</head>
<body>
<div class="reveal">
<!-- Any section element inside of this container is displayed as a slide -->
<div class="slides">
<section>
<h1>Such Java,<br>Much Script!</h1>
<h3><a>An introduction to JavaScript</a></h3>
<p>
<small>Steve De Jonghe</small>
</p>
</section>
<section>
<h2>Mandatory introduction slide</h2>
<ul class="bare">
<li>Steve De Jonghe</li>
<li>Intertubes plumber @ <a href="http://wunderkraut.com">Wunderkraut</a> <a href="http://wunderkraut.be">Belgium</a> (Antwerp office)</li>
</ul>
</section>
<section>
<h2>Overview</h2>
<ul class="bare">
<li>Preface</li>
<li>Types</li>
<li>Type coercion</li>
<li>Truthy falsy</li>
<li>Arrays</li>
<li>Objects</li>
<li>Functions: Scope, 'this', async, chaining, instances, inheritance</li>
<li>The DOM: Traversal, doc.rdy</li>
<li>Events: Bubbling, propagation, delegating</li>
<li>Ajax: More async</li>
</ul>
</section>
<section>
<section>
<h2>Preface</h2>
</section>
<section>
<h2>Preface</h2>
<h3>Tooling</h3>
<ul>
<li>The browser is your #1 tool for writing JavaScript:
<ul>
<li>Fully fledged IDE with all the debugging tools you could possible want</li>
<li>Allows conditional breakpoint</li>
<li>Allows breaking on things non-code (subtree modification, etc)</li>
<li>Allows <a href="https://chrome.google.com/webstore/detail/custom-redirects/kekdllcidamgebonidegjekidhdihdli/" title="Chrome custom redirects">swapping remote files</a> with locals ones at-runtime</li>
<li>Allows beautifying production code</li>
<li><a href="https://getfirebug.com/wiki/index.php/Console_API" target="_blank">Console API</a></li>
<li>much, much more! (like <a href="https://www.youtube.com/watch?v=ktwJ-EDiZoU&list=PLVUliVBcvz1n_DOgB4lb06G_Dc5fQVRRv">The Breakpoint</a>)</li>
</ul>
</li>
</ul>
</section>
<section>
<h2>Preface</h2>
<h3>Error prevention</h3>
<ul>
<li>The linter is you friend!</li>
<li>No, seriously, it will tell you to use semicolons and ===, which will save you countless hours!</li>
</ul>
</section>
</section>
<section>
<section>
<h2>Types</h2>
<h3>They see me coercing...</h3>
</section>
<section>
<h2>Everything is an object, except <a href="https://developer.mozilla.org/en-US/docs/Glossary/Primitive">primitives</a>:</h2>
<ul class="bare">
<li><a href="https://developer.mozilla.org/en-US/docs/Glossary/Null">null</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Glossary/undefined">undefined</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Glossary/Number">number</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Glossary/Boolean">boolean</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Glossary/String">string</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Glossary/Symbol">(symbol)</a></li>
</ul>
</section>
<section>
<h2>Primitives vs Objects</h2>
<ul class="bare">
<li>Primitives cannot be broken down to an extended type and cannot be assigned custom properties.</li>
<li>Primitives are not passed by reference.</li>
<li>All the rest are essentially extended Objects (Array, Date, etc.) and are passed by reference.</li>
<li>Use literal notation where possible, avoid using new keyword on base type object wrappers</li>
</ul>
<pre><code class="language-javascript" data-trim>
typeof 'foo'; // "string" - Good
typeof String('foo'); // "string" - Not so good
typeof new String('foo'); // "object" - Bad
typeof (new String('foo')).valueOf(); // "string" - Awkward
(new String('foo')) === 'foo'; // false - o.O
</code></pre>
</section>
<section>
<h2>Cautionary note on <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof">typeof</a></h2>
<p>It lies!</p>
<pre><code class="language-javascript" data-trim>
typeof null; // "object"
typeof []; // "object"
typeof /regex/; // "function" in some browsers
</code></pre>
</section>
<section>
<h2>Dead set on matching the type?</h2>
<p>
Force the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString">Object.toString</a> method to do your bidding!
</p>
<pre><code class="language-javascript" data-trim>
Object.prototype.toString.call(null); // "[object Null]"
Object.prototype.toString.call([]); // "[object Array]"
Object.prototype.toString.call(/regex/); // "[object RegExp]"
</code></pre>
<p>(More on prototypes and function methods later!)</p>
<aside class="notes">
<p><small>If you need this, you probably have a bigger problem.</small></p>
</aside>
</section>
<section>
<h2>Cautionary note on numbers</h2>
<ul>
<li>Floating point!<br><pre><code class="language-javascript" data-trim>0.2 + 0.2 + 0.2; // 0.6000000000000001 WAT?!</code></pre></li>
<li>don't care about precision?
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed">Number.toFixed()</a> to determine float precision<br><pre><code class="language-javascript">(0.2 + 0.2 + 0.2).toFixed(2); // 0.60</code></pre></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt">parseInt()</a> with a radix<br><pre><code class="language-javascript">parseInt(42.56789, 10); // 42(!)</code></pre></li>
</ul>
</li>
<li>Working with currency? Do everything in cents or use a library to provide <a href="https://github.com/MikeMcl/big.js">bigger decimals with arbitrary precision</a></li>
</ul>
</section>
<section>
<h2>Bonus!</h2>
<pre><code class="language-javascript" data-trim>
var foo = new Number(0);
foo === 0; // "false" - foo is an obj, 0 is an int.
foo == 0; // "true" - so foo is falsy?
!!foo; // "true" - I guess not o.O
</code></pre>
</section>
<section>
<h2>Cautionary note on strings</h2>
<ul>
<li>Not as bad as PHP, but still pretty weird sometimes.</li>
<li><strong>parseInt() if you want to do maths, always provide radix parameter!</strong>
<pre><code class="language-javascript" data-trim>
parseInt('042'); // Some browsers will default to octal 66.
parseInt('042', 10); // Force parsing as decimal.
parseInt('12foo34', 10); // 12 (!)
</code></pre>
</li>
</ul>
</section>
<section>
<h2>More caution</h2>
<ul>
<li>Unicode handling can be a bit wonky
<pre><code class="unicode language-javascript" data-trim>
var poo = '💩';
poo.length; // 2
poo.split('').reverse().join(''); // "��"
poo === '\uD83D\uDCA9'; // true
</code></pre>
<pre><code class="languae-javascript" data-trim>
var a = 'se\xF1orita'; // "señorita"
var b = 'sen\u0303orita'; // "señorita"
a == b; // false
a.length; // 8
b.length; // 9
</code></pre>
</li>
<li>Use <a href="https://github.com/bestiejs/punycode.js">Punycode.js</a> or <a href="https://mathiasbynens.be/notes/javascript-unicode">funky regex</a> if you need to support astral plane characters.</li>
</ul>
</section>
<section>
<h2>Bonus!</h2>
<ul>
<li>They can be partially accessed like an array (mainly getters).</li>
</ul>
<pre><code class="language-javascript" data-trim>
var foo = 'foo';
foo[0]; // 'f'
foo[0] = 'p'; // Nice try, no setters tho!
foo.split('f').join('p'); // 'poo' (like PHPs explode/implode)
foo.length; // 3
foo.bar = 'baz'; // Nice try, primitives can't have properties tho!
foo.bar; // undefined
</code></pre>
<p>This is often referred to as "<em>Array-like</em>", but should not be considered a fully-fledged array.</p>
</section>
<section>
<h2>Bonus Bonus!</h2>
<pre><code class="language-javascript" data-trim>
var foo = new String('foo');
// Secretly an object wrapper pretending to be a string
foo === 'foo'; // false
foo == 'foo'; // true
foo.lol = 'lol'; // now it actually sticks!
foo.lol; // 'lol'
</code></pre>
</section>
</section>
<section>
<section>
<h2>Type coercion</h2>
<h3>The operator matters!</h3>
<p>With strings and numbers, the + operator will coerce everything to strings</p>
<pre><code class="language-javascript" data-trim>
'123' + 4; // '1234'
1 + '234'; // '1234'
</code></pre>
<p>Likewise, the - operator will coerce everything to a number</p>
<pre><code class="language-javascript" data-trim>
'123' - 4; // 119
1 - '234' ; // -233
</code></pre>
</section>
<section>
<h2>Type coercion</h2>
<h3>cheap casting!</h3>
<p>Using the unary + operator, we can easily cast to a number.</p>
<p>This works similar to <code>parseFloat()</code>, except it will return NaN if any part of the string could not be parsed.</p>
<pre><code class="language-javascript" data-trim>
'1.23' + '1.23'; // '1.231.23' (string)
(+'1.23') + (+'1.23'); // 2.46 (parens optional)
+'1.23' + + '1.23'; // 2.46
+'1.23'; // 1.23
+'1.23.23'; // NaN (!!)
+'1.999999999999999'; // 1.999999999999999
+'1.9999999999999999'; // 2
</code></pre>
<p>This does not save you from <code>NaN</code>ty<code>NaN</code> problems though, always check user input!</p>
</section>
<section>
<h2>Truthy falsy</h2>
<h3>What !!is and what !is?</h3>
<p>The following values are considered not "truthy" and will coerce to <code>false</code>:<br><code>undefined</code>, <code>null</code>, <code>NaN</code>, <code>0</code>, <code>''</code></p>
<p>Gotcha: <code>!!'0'; // "true"</code></p>
</section>
<section>
<h2>Truthy falsy</h2>
<h3>Shortcuts</h3>
<pre><code class="language-javascript" data-trim>
// someInit will not be executed unless someVar is falsy
var foo = someVar || someInit();
// Useful for defaults!
var bar = function (x) {
x = x || myDefaults;
};
// Or checks!
var ready = someInit() && attachThatNeedsToRunAfterInit();
</code></pre>
</section>
</section>
<section>
<section>
<h2>The mighty Array!</h2>
<ul>
<li>Unlike in PHP, array keys can only be numeric, using string keys on an array will cause it to show its underlying object-like nature.<pre><code class="language-javascript" data-trim>
var foo = ['poo'];
foo.length; // 1
foo.bar = 'bar';
foo.length; // 1
foo.bar; // 'bar' (foo['bar'] also works)
foo; // ['poo']
</code></pre></li>
<li>For example: jQuery's $() query returns an array-like object of results that's augmented with properties and methods.</li>
</ul>
</section>
<section>
<h2>The mighty Array!</h2>
<ul>
<li>Avoid manually assigning keys, missing ones will be undefined. Instead, use Array.push().<pre><code class="language-javascript" data-trim>
var foo = ['lala', 'hihi'];
foo.push('hoho'); // 3 (Array.push returns new length)
foo[7] = 'lolapi';
foo.length; // 8
foo[6]; // undefined
</code></pre></li>
</ul>
</section>
<section>
<h2>The mighty Array!</h2>
<ul>
<li><strong>Never ever</strong> for...in loop on an array, use a regular for-loop!
<pre><code class="language-javascript" data-trim>
var foo = ['bar'];
foo.lol = 'gotcha!';
for (var i in foo) {
console.log(foo[i]); // 'bar', 'gotcha!'
}
for (var i = 0, len = foo.length; i < len; i++) {
console.log(foo[i]); // 'bar'
}
</code></pre></li>
</ul>
<p>Don't care about IE8?<br>Use <code>Array.forEach(callback)</code> (note: unbreakable!)</p>
</section>
</section>
<section>
<h2>The even mightier Object!</h2>
<ul>
<li>Basis for most types in JavaScript.</li>
<li>Changing its prototype affects nearly everything.</li>
<li>for..in loops loop over properties from the entire chain!
<pre><code class="language-javascript">Object.prototype.lol = 'lolapi';
var foo = {'meh': 'poo'};
for (var key in foo) {
console.log(key); // 'meh', 'lol'
if (foo.hasOwnProperty(key)) {
console.log(key); // Just 'meh'
}
}</code></pre>More on inheritence later!</li>
</ul>
</section>
<section>
<section>
<h2>The mightiest: Function</h2>
<h3>Creator of scope</h3>
<pre><code class="language-javascript" data-trim>
function foo() {
var bar = 'lol';
}
foo();
console.log(bar); // undefined
</code></pre>
<pre><code class="language-javascript" data-trim>
var bar = 'lol';
function foo(bar) {
return bar;
}
console.log(foo()); // undefined
</code></pre>
</section>
<section>
<h2>Function: Creates scope</h2>
<h3>Immediately Invoked Function Expression</h3>
<pre><code class="language-javascript" data-trim>
var x = 'bar';
(function (x) {
x === 'foo'; // true
})('foo');
x === 'bar'; // true
// Roughly equivalent (without accessible leftovers)
var foo = function(x) {}
foo('foo');
</code></pre>
</section>
<section>
<h2>Function: Creates scope</h2>
<h3>Immediately Invoked Function Expression</h3>
<pre><code class="language-javascript" data-trim>
(function (x, y) {
x === 'foo'; // true
y === window; // true if in a browser and not hosed outside scope
var foo = "I won't leak to the global scope!";
y.bar = "I will!"; // same as window.bar
})('foo', this);
foo; // undefined
bar; // "I will!"
</code></pre>
</section>
<section>
<h2>Function: IIFE</h2>
<h3>Why is this useful?</h3>
<pre><code class="language-javascript" data-trim>
(function(window){
// Scoped variable.
var myPrivate = 'foo';
// Intentionally leaked getter function to the global scope.
window.getPrivate = function() {
// function is defined within same scope so it can access the var
return myPrivate;
};
})(this);
getPrivate(); // 'foo'
myPrivate; // ReferenceError: myPrivate is not defined
</code></pre>
</section>
<section>
<h2>The mightiest: Function</h2>
<h3>Can return functions</h3>
<pre><code class="language-javascript" data-trim>
function compute (x) {
return function (y) {
return x*y;
}
}
compute(2)(3); // 6
</code></pre>
</section>
<section>
<h2>The mightiest: Function</h2>
<h3>And so much more!</h3>
<pre><code class="language-javascript" data-trim>
function maths(x) {
return {
compute: function(y) {
return x * y;
},
add: function(y) {
return x + y;
},
abs: Math.abs(x)
}
}
maths(2).compute(3); // 6
maths(2).add(3); // 5
maths(-2).abs; // 2
</code></pre>
</section>
<section>
<h2>The mighties: Function</h2>
<h3>"this" is madness!</h3>
<pre><code class="language-javascript" data-trim>
var foo = {
a: 'lol',
b: function() {
return this.a;
}
};
foo.b(); // 'lol'
var bar = foo.b;
bar(); // undefined
</code></pre>
<p>Here, <code>bar</code> is actually <code>window.bar</code>, so the window object becomes the context, and there is no <code>window.a</code>.</p>
</section>
<section>
<h2>The mightiest: Function</h2>
<h3>Special methods and magic "this"!</h3>
<pre><code class="language-javascript" data-trim>
var foo = function() {
return this;
}
// Create a clone of the function with a fixed context of 'bar!'.
var bar = foo.bind('bar!');
foo(); // returns reference to the window object.
bar(); // 'bar!'
// Call foo in the context of 'lol'
foo.call('lol'/* , arg1, arg2 */); // 'lol'
foo.apply('lol'/* , [arg1, arg2] */); // 'lol'
</code></pre>
</section>
<section>
<h2>The mightiest: Function</h2>
<h3>So how do I function?</h3>
<pre><code class="language-javascript" data-trim>
// Defined at run-time.
foo(); // TypeError: undefined is not a function
var foo = function () {};
</code></pre>
<pre><code class="language-javascript" data-trim>
// Defined at parse-time for this block.
foo(); // no error
function foo() {};
</code></pre>
</section>
<section>
<h2>The mightiest: Function</h2>
<h3>What is even going on here?</h3>
<pre><code class="language-javascript" data-trim>
// Essentially an anonymous function stored in a variable.
var foo = function () { };
foo.name; // '' (empty string)
</code></pre>
<pre><code class="language-javascript" data-trim>
// A named function.
function foo() { };
foo.name; // 'foo'
</code></pre>
<pre><code class="language-javascript" data-trim>
// But wait!
var foo = function bar() { };
foo.name; // 'bar'
bar.name; // ReferenceError: bar is not defined
// WAT?!
</code></pre>
</section>
<section>
<h2>The mightiest: Function</h2>
<h3>I don't even...?</h3>
<pre><code class="language-javascript" data-trim>
var foo = function bar() {
bar.meh = function() { return bar.name; };
};
foo(); // Calling it makes it give itself the "meh" method.
foo.meh(); // "bar"
</code></pre>
</section>
<section>
<h2>The mightiest: Functions</h2>
<h3>Bonus points!</h3>
<pre><code class="language-javascript" data-trim>
// We can return ourselves!
var foo = function bar() {
// Do some things...
return bar;
};
foo.name; // 'bar'
foo().name; // 'bar'
foo()()()()()()()(); // ...
</code></pre>
</section>
<section>
<h2>Intermission</h2>
<h3>Hoisting</h3>
<p>Variable and function declarations are invisibly moved to the top of their scope</p>
<pre><code class="language-javascript" data-trim>
one(); // TypeError "one is not a function"
two(); // Works.
three(); // TypeError "three is not a function"
four(); // ReferenceError "four is not defined"
var one = function() {}; // Anonymous function expression.
function two() {}; // Function declaration.
var three = function four() {}; // Named function expression.
one(); // Works.
two(); // Works.
three(); // Works.
four(); // ReferenceError "four is not defined"
</code></pre>
</section>
<section>
<h2>Intermission!</h2>
<h3>Hoisting</h3>
<p>Actual interpretation</p>
<pre><code class="language-javascript" data-trim>
var one, three; // Variable name is "hoisted" to top of scope.
function two() {}; // Entire function declaration gets hoisted.
one(); // TypeError "one is not a function"
two(); // Works.
three(); // TypeError "three is not a function"
four(); // ReferenceError "four is not defined"
one = function() {}; // Anonymous function expression.
three = function four() {}; // Named function expression.
one(); // Works.
two(); // Works.
three(); // Works.
four(); // ReferenceError "four is not defined"
</code></pre>
</section>
<section>
<h2>The mightiest: Functions</h2>
<h3>Why is this even useful?</h3>
<pre><code class="language-javascript" data-trim>
// Remember, we're also an object.
var foo = function bar(op) {
// Fixed internal reference!
bar.doStuff = function() {
// Do stuff
return bar;
};
bar.doMoreStuff = function() {
// Do more stuff
return bar;
};
if (op && bar[op]) { // if an op was passed and it exists
return bar[op](); // call it and return the return
}
return bar; // Return ourselves
};
foo().doStuff().doMoreStuff(); // or foo('doStuff')('doMoreStuff')...
</code></pre>
</section>
<section>
<h2>The mightiest: Functions</h2>
<h3>Callbacks & setTimeout/setInterval</h3>
<pre><code class="language-javascript" data-trim>
// Logs 'HOLAS!' every second.
var foo = function() {
console.log('HOLAS!');
window.setTimeout(foo, 1000);
};
window.setTimeout(foo, 1000);
// Bad:
var bar = function() {
console.log('What if I took more than 1 second to run?');
};
window.setInterval(bar, 1000);
</code></pre>
</section>
<section>
<h2>The mightiest: Functions</h2>
<h3>AJAX</h3>
<pre><code class="language-javascript" data-trim>
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
doStuffWithData(JSON.parse(xhr.responseText));
}
}
};
xhr.open('GET', '/lol', true);
// xhr.setRequestHeader('Content-Type', 'some/mime-type');
xhr.send();
</code></pre>
</section>
<section>
<h2>The mightiest: Functions</h2>
<h3>So how do I instance?</h3>
<pre><code class="language-javascript" data-trim>
// Define it as a constructor.
function Foo() { // capital is just convention
this.bar = function() { return this; }; // Note the "this"
};
var one = new Foo(); // Note the "new"
var two = new Foo();
one === two; // false, they are 2 separate instances
one.bar() === two.bar(); // false
one.bar() === one; // true
one instanceof Foo; // true
Foo(); // note the absence of "new"
window.bar; // We just hosed the global scope
</code></pre>
</section>
<section>
<h2>The mightiest: Functions</h2>
<h3>Inheritance</h3>
<pre><code class="language-javascript" data-trim>
// Set up constructor.
var Foo = function() {
this.bar = 0;
};
// Define its base object.
Foo.prototype = {
addBar: function() { this.bar++; }
};
var foo = new Foo(); // foo > Foo.prototype > Object.prototype > null
foo.addBar();
foo.bar; // 1
Object.getPrototypeOf(foo).bar; // undefined (not available in IE<9)
Foo.prototype.meh = 'lol';
foo.meh; // 'lol'
</code></pre>
</section>
<section>
<h2>The mightiest: Functions</h2>
<h3>Inheritance</h3>
<pre><code class="language-javascript" data-trim>
var Foo = function() {
this.bar = 0;
this.addBar = function() { return ++this.bar; };
};
var Bar = function() {
this.addBar = function(i) { this.bar = this.bar + i; return this.bar; };
};
Bar.prototype = new Foo(); // Set Bar's prototype to new instance of Foo
var foo = new Foo(); // Foo.prototype is essentially an empty object
var bar = new Bar(); // bar > Bar.prototype (Foo) > Foo.prototype ({}) > Object.prototype > null
bar.addBar(7); // 7
foo.addBar(7); // 1
bar.bar; // 7
Bar.prototype.meh = 'lol';
bar.meh; // 'lol'
foo.meh; // undefined
</code></pre>
</section>
<section>
<h2>The mightiest: Functions</h2>
<h3>Inheritance</h3>
<pre><code class="language-javascript" data-trim>
var Foo = function() {
this.bar = 0;
this.addBar = function() { return ++this.bar; };
};
var Bar = function() {
this.addBar = function(i) { this.bar = this.bar + i; return this.bar; };
this.callSuper = function(op, arg) {
return Object.getPrototypeOf(this)[op].call(this, arg);
};
}
Bar.prototype = new Foo();
var foo = new Foo();
var bar = new Bar();
bar.callSuper('addBar', 7); // 1
</code></pre>
</section>
<section>
<h2>Who wants constructors anyway?</h2>
<h3>Keeping things light</h3>
<pre><code class="language-javascript" data-trim>
function create(parent) { // aka "justMakeMeAnObjectThatInheritsFromThis"
var Constructor = function () {}; // Empty constructor function
Constructor.prototype = parent; // Attach prototype object
// Return new instance, inheriting from parent
return new Constructor();
}
var a = { foo: 'lol' };
var b = create(a);
b.foo; // 'lol'
a.bar = 'baz';
b.bar; // 'baz'
b.meh = 'nope';
a.meh; // undefined
</code></pre>
</section>
</section>
<section>
<section>
<h2>Enter: Object.create</h2>
<h3>Syntax</h3>
<pre><code class="language-javascript" data-trim>
Object.create(proto /*[, props ]*/)
</code></pre>
<h3>Summary</h3>
<p>The <strong>Object.create()</strong> method creates a new object with the specified prototype object and properties.</p>
<h4>Arguments</h4>
<p><em>proto</em>: The object which should be the prototype of the newly-created object.</p>
<p><em>props</em>: An object whose enumerable own properties specify property descriptors to be added to the newly-created object, with the corresponding property names.</p>
</section>
<section>
<h2>Enter: Object.create</h2>
<h3>Polyfill (IE<9)</h3>
<pre><code class="language-javascript" data-trim>
if (typeof Object.create != 'function') {
(function () {
var F = function () {};
Object.create = function (o) {
if (arguments.length > 1) { throw Error('Second argument not supported');}
if (o === null) { throw Error('Cannot set a null [[Prototype]]');}
if (typeof o != 'object') { throw TypeError('Argument must be an object');}
F.prototype = o;
return new F();
};
})();
}
</code></pre>
</section>
</section>
<section>
<h2>In the wild!</h2>
<h3>From BackBone source:</h3>
<pre><code class="language-javascript" data-trim>
var extend = function(protoProps, staticProps) {
var parent = this;
var child;
if (protoProps && _.has(protoProps, 'constructor')) {
child = protoProps.constructor;
} else {
child = function(){ return parent.apply(this, arguments); };
}
_.extend(child, parent, staticProps);
var Surrogate = function(){ this.constructor = child; };
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate;
if (protoProps) _.extend(child.prototype, protoProps);
child.__super__ = parent.prototype;
return child;
};
</code></pre>
</section>
<section>
<h2>The DOM</h2>
<h3>Object with many fingers in many things</h3>
<ul>
<li>Object-tree representation of entire document</li>
<li>Contains and exposes most of the APIs we use</li>
<li>Used to be really, really, really annoying, now just really really</li>
<li>Traversing this mess is the main purpose of libraries like jQuery</li>
<li>Manipulations (and some getters, even) are costly and should be kept to a minimum.</li>
</ul>
</section>
<section>
<h2>Traversal</h2>
<h3>All the nesting!</h3>
<pre><code class="language-javascript" data-trim>
// [ <html element> ]
document.children;
// [ <head element>, <body element> ]
document.children[0].children;
// [ <element with class someClass>, <...> ]
document.getElementsByClassName('someClass');
// equivalent (note: IE8 only supports CSS2 selectors)
document.querySelectorAll('.someClass');
</code></pre>
</section>
<section>
<h2>Caution!</h2>
<h3>Document ready</h3>
<p>Remember: You cannot query for an element if it hasn't been parsed yet. Place scripts at the bottom or use things like jQuery's <code>$(document).ready(function() { ... })</code></p>
<pre><code class="language-html" data-trim>
<html>
<head>
<script>
//TypeError: Cannot read property 'querySelector' of null
var foo = document.body.querySelector('.foo');
</script>
</head>
<body>
<div class="foo">foo</div>
<script>
// Works fine
var foo = document.body.querySelector('.foo');
</script>
</body>
</html>
</code></pre>
</section>
<section>
<h2>Caution!</h2>
<p>As mentioned before, array-like does not mean it's an array.</p>
<pre><code class="language-javascript" data-trim>
var foo = document.querySelectorAll('.foo');
foo.forEach; // undefined - does not have array method.
// Invoke array method in the context of our collection.
Array.prototype.forEach.call(foo, function(el) { // Pass in anonymous function
console.log(el); // logs out each element separately.
});
</code></pre>
</section>
<section>
<h2>The driving force of it all: Events</h2>
<h3><a href="events.html" target="_blank">Bubbles!</a></h3>
<pre><code class="language-javascript" data-trim>
// Define a handler for our events.
var handler = function(event) { console.log(this, event.target); },
body = window.document.body, // Cache some element references.
form = body.querySelector('form'),
button = form.querySelector('input[type="button"]');
// Add our event listener to the cached references.
body.addEventListener('click', handler);
form.addEventListener('click', handler);
button.addEventListener('click', handler);
</code></pre>
</section>
<section>
<h2>The driving force of it all: Events</h2>
<h3><a href="stopPropagation.html" target="_blank">Event methods: stopPropagation!</a></h3>
<pre><code class="language-javascript" data-trim>
// Handler that calls stopPropagation on the event.
var handler = function(event) {
console.log(this, event.target);
event.stopPropagation();
},
body = window.document.body, // Cache some element references.
form = body.querySelector('form'),
button = form.querySelector('input[type="submit"]');
// Add our event listener to the cached references.
body.addEventListener('click', handler);
form.addEventListener('click', handler);
button.addEventListener('click', handler);
</code></pre>
</section>
<section>
<h2>The driving force of it all: Events</h2>
<h3><a href="preventDefault.html" target="_blank">Event methods: preventDefault!</a></h3>
<pre><code class="language-javascript" data-trim>
// Handler that calls preventDefault on the event.
var handler = function(event) {
event.preventDefault();
},
form = window.document.body.querySelector('form');
// The handler will effectively prevent
// the native submit event from happening.
form.addEventListener('submit', handler);
</code></pre>
</section>
<section>
<h2>The driving force of it all: Events</h2>
<h3><a href="delegating.html" target="_blank">Advanced techniques: Delegating!</a></h3>
<pre><code class="language-javascript" data-trim>
(function(window) {
var handler = function(event) {
// Only act if the actual target is '.foo'
if (event.target.className === 'foo') {
event.preventDefault();
console.log('Do something!');
}
};
// Attach the handler to the entire body element.
window.document.body.addEventListener('click', handler);
})(this);
</code></pre>
<p>Like jQuery's <code>$.fn.on()</code>, <code>$.fn.delegate</code>, ...</p>
</section>
<section>
<h2>The driving force of it all: Events</h2>
<h3>All the async!</h3>