-
Notifications
You must be signed in to change notification settings - Fork 0
/
You Don't Know JS.txt
2602 lines (1790 loc) · 121 KB
/
You Don't Know JS.txt
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
WHAT IS SCOPE?
Scope is the set of rules that determine where and how a variable can be looked-up.
- LHS(Left-Hand Side):
Assignment of value to the variable.
- RHS(Right-Hand Side):
Retrieve the value of the variable.
LEXICAL SCOPE
Scope is defined by decisions of where functions are declared.
Compilation consists of three steps:
1) Tokens
2) Parsing
3) Code generation
FUNCTION VS BLOCK SCOPE
Units of scope:
- Function:
Any variable declared inside a function is hidden from any enclosing scope.
- Block
Any variable declared inside a block ({}).
It's a good practice to hide code in function scopes from other scopes to avoid collision and scope polution. Instead of declaring a function and then invoking it, use IIFE (Immediately Invoked Function Expession):
(function foo(){
...
})();
- var always belongs to the enclosing scope/function scope.
- let is block scoped.
- const is block scoped but with a fixed value.
HOISTING
Declaration of variables occur in compilation and assignment of values at execuiton time. It's as if declarations are moved to the top of their respective scope. const and let are not hoisted.
CLOSURE
It's when a function can remember and access it's lexical scope even when invoked outside of it´s lexical scope. Functions treated as first-class values passed around (as parameters e.g. callback) are clear examples of closure.
function foo() {
var a = 2;
function bar() {
console.log( a );
}
return bar;
}
var baz = foo();
baz(); // 2 -- Whoa, closure was just observed, man. bar() still has a reference to it's lexical scope.
for (var i=1; i<=5; i++) {
setTimeout( function timer(){
console.log( i );
}, i*1000 );
}// Prints 6 5 times
for (var i=1; i<=5; i++) {
(function(){
var j = i;
setTimeout( function timer(){
console.log( j );
}, j*1000 );
})();
}// The IIFE creates a scope for j to be declared and immediately assigns it's value by being immediately invoked
for (let i=1; i<=5; i++) {
setTimeout( function timer(){
console.log( i );
}, i*1000 );
}// The variable is declared for each iteration of the loop
Closures enable a pattern called modules, which require:
1) An outer wrapping function being invoked, to create the enclosing scope.
2) The return value must include reference to at least one inner function that has closure over the private inner scope of the wrapping function.
----------------------------------------------------------------------------------------------------
THIS
this is a binding made when a function is invoked and what it points to is determined entirely by the call-site.
- callstack:
the stack of functions that have been called to get to the current moment in execution.
- call-site:
the location in code where a function is called (not where it's declared). For 'this' binding, the call-site we care about is in the invocation before the currently executing function.
THE 4 RULES
- DEFAULT BINDING
Standalone function invocation, when no other rules apply. Resolves to purely locating the call-site for 'this' binding.
function foo() {
console.log( this.a );
}
var a = 2;
foo(); // 2
If strict mode is enabled, the global scope is not elegible for default binding, so 'this' is set to undefined. Only if the contents of the function using 'this' are in strict mode.
- IMPLICIT BINDING
The call-site has a context object, called "owning/containing object". The call-site uses the object context to reference a function, 'this' is binded to that object.
function foo() {
console.log( this.a );
}
var obj = {
a: 2,
foo: foo
};
obj.foo(); // 2
IMPLICITLY LOST
Implicitly bound functions can lose their binding, so they fallback to the default binding, global object or undefined, in two cases:
1) Function reference/alias to the "containing object" function:
function foo() {
console.log( this.a );
}
var obj = {
a: 2,
foo: foo
};
var bar = obj.foo; // function reference/alias!
var a = "oops, global"; // `a` also property on global object
bar(); // "oops, global"
Note: bar is only a reference to foo and the call-site is bar() so the default binding applies.
2) Callbacks (etiher our own callbacks or built-in to the language):
function foo() {
console.log( this.a );
}
function doFoo(fn) {
// `fn` is just another reference to `foo`
fn(); // <-- call-site!
}
var obj = {
a: 2,
foo: foo
};
var a = "oops, global"; // `a` also property on global object
doFoo( obj.foo ); // "oops, global"
Note: Parameter passing is just an implicit assignment, so the end result is the same as the previous case.
- EXPLICIT BINDING
The function utilises either call, apply or bind, taking as their first parameter the object to use for 'this'.
function foo() {
console.log( this.a );
}
var obj = {
a: 2
};
foo.call( obj ); // 2
But this still doesn´t fix the problem of a function losing it's binding, that's why we need a variation if it:
HARD BINDING
Create a function which internally manually explicitly calls the function to be bound, thereby invoking the function with that object always bound.
function foo() {
console.log( this.a );
}
var obj = {
a: 2
};
var bar = function() {
foo.call( obj );
};
bar(); // 2
setTimeout( bar, 100 ); // 2
// `bar` hard binds `foo`'s `this` to `obj`
// so that it cannot be overriden
bar.call( window ); // 2
The most typical way to wrap a function with a hard binding is creating a re-usable helper, which creates a pass-thru of any arguments passed and any return value recived:
function foo(something) {
console.log( this.a, something );
return this.a + something;
}
// simple `bind` helper
function bind(fn, obj) {
return function() {
return fn.apply( obj, arguments );
};
}
var obj = {
a: 2
};
var bar = bind( foo, obj );
var b = bar( 3 ); // 2 3
console.log( b ); // 5
Since hard binding is such a common pattern, it´s provided with ES5, returning a new function that is hard-coded to call the original function with 'this' context set as specified:
function foo(something) {
console.log( this.a, something );
return this.a + something;
}
var obj = {
a: 2
};
var bar = foo.bind( obj );
var b = bar( 3 ); // 2 3
console.log( b ); // 5
Many libraries functions and built-in functions in JS (like array functions), provide an optional parameter, which is designed as a work-around for not having to use bind, but internally they use explicit binding.
- NEW BINDING
In JS constructors are just functions that happen to be called with the word 'new' in front of them, they are not attached to classes, nor instantiating a class. Pretty much any function can be called with the word new, making it a constructor call of a function. When this happens:
1) A new object is created (constructed).
2) The new object is [[Prototype]] linked.
3) The new object is set as the 'this' binding of that function call.
4) Unless the function returns it's own alternate object, the new object is returned.
function foo(a) {
this.a = a;
}
var bar = new foo( 2 );
console.log( bar.a ); // 2
ORDER OF THE 4 RULES
1) Is the function called with new (new binding)? If so, this is the newly constructed object.
var bar = new foo()
2) Is the function called with call or apply (explicit binding), even hidden inside a bind hard binding? If so, this is the explicitly specified object.
var bar = foo.call( obj2 )
3) Is the function called with a context (implicit binding), otherwise known as an owning or containing object? If so, this is that context object.
var bar = obj1.foo()
4) Otherwise, default the this (default binding). If in strict mode, pick undefined, otherwise pick the global object.
var bar = foo()
CURRYING
The primary reason for new > explicit, is to create a function that ignores the explicit 'this' binding but presents the function's arguments. On of the capabilities of 'bind' is that any arguments passed after 'this' are defaulted as argument for the underlying function.
function foo(p1,p2) {
this.val = p1 + p2;
}
// using `null` here because we don't care about
// the `this` hard-binding in this scenario, and
// it will be overridden by the `new` call anyway!
var bar = foo.bind( null, "p1" );
var baz = new bar( "p2" );
baz.val; // p1p2
IGNORED THIS
In explicit binding you can ignore 'this' by passing null, this is common for spreading arrays or currying:
function foo(a,b) {
console.log( "a:" + a + ", b:" + b );
}
// spreading out array as parameters
foo.apply( null, [2, 3] ); // a:2, b:3
// currying with `bind(..)`
var bar = foo.bind( null, 2 );
bar( 3 ); // a:2, b:3
There's a danger of passing null, in some cases (like third parties) can make a reference to 'this', applying the default binding and making a reference to the global object. Which is better to use, instead of null, something like this:
var ø = Object.create( null );
LEXICAL THIS
Arrow functions don't abide by the 4 rules, instead they adopt the 'this' binding from the enclosing scope.
function foo() {
// return an arrow function
return (a) => {
// `this` here is lexically adopted from `foo()`
console.log( this.a );
};
}
var obj1 = {
a: 2
};
var obj2 = {
a: 3
};
var bar = foo.call( obj1 );
bar.call( obj2 ); // 2, not 3!
The arrow function created by foo captures 'this' at call-time. Since foo's 'this' was bound to obj1, bar's 'this' will too. Lexical binding of arrow functions cannot be overriden by any of the 4 rules.
The most common case of arrow functions are callbacks:
function foo() {
setTimeout(() => {
// `this` here is lexically adopted from `foo()`
console.log( this.a );
},100);
}
var obj = {
a: 2
};
foo.call( obj ); // 2
Which is basically:
function foo() {
var self = this; // lexical capture of `this`
setTimeout( function(){
console.log( self.a );
}, 100 );
}
var obj = {
a: 2
};
foo.call( obj ); // 2
----------------------------------------------------------------------------------------------------
OBJECTS
Can be created in two forms:
- LITERAL:
var myObj = {
key: value
// ...
};
- CONSTRUCTED FORM:
var myObj = new Object();
myObj.key = value;
TYPES
There are 6 primary types in JS:
- string
- number
- boolean
- null
- undefined
- object
The first 5 are called simple primitives and they are not objects.
There are a few special object sub-types, called complex primitives:
- function
A "callable object". Functions in JS are "first class" which means they can be handle like any other plain object.
- arrays
Objects with extra behavior. The organization of contents in arrays is more structured than general objects.
BUILT-IN OBJECTS
There are other object sub-types (note first letter is uppercase):
- String
- Number
- Boolean
- Object
- Function
- Array
- Date
- RegExp
- Error
These have the appearance of being actual types, even clases. But in JS they are just built-in constructors (function call with a 'new' opeartor) with the result being a newly constructed object of the subtype in question:
var strPrimitive = "I am a string";
typeof strPrimitive; // "string"
strPrimitive instanceof String; // false
var strObject = new String( "I am a string" );
typeof strObject; // "object"
strObject instanceof String; // true
To perform operations on them (like checking length) a String object is required. Luckily JS automatically creates these from the "string" object when necessary.
CONTENTS
The contents of an object consist of values stored at specifically named locations, called properties.
To acces a value at a location, we can use:
- Property access
myObject.a
- Key access
myObject["a"]
Property access requires an Identifier compatible property and key access can take basicallly any string as the name of the property. So with key access we can programaticallly build up the value of the string property name.
var wantA = true;
var myObject = {
a: 2
};
var idx;
if (wantA) {
idx = "a";
}
// later
console.log( myObject[idx] ); // 2
In objects, property names are always strings. So if you use any other value other than a string, JS will first convert the value to string.
var myObject = { };
myObject[true] = "foo";
myObject[3] = "bar";
myObject[myObject] = "baz";
myObject["true"]; // "foo"
myObject["3"]; // "bar"
myObject["[object Object]"]; // "baz"
COMPUTED PROPERTY NAMES
ES6 adds the ability to specify an expression, surrounded by [], in the property name position of an object literal declaration:
var prefix = "foo";
var myObject = {
[prefix + "bar"]: "hello",
[prefix + "baz"]: "world"
};
myObject["foobar"]; // hello
myObject["foobaz"]; // world
ARRAYS
Arrays are objects that have a better organization for how and where values are stored:
var myArray = [ "foo", 42, "bar" ];
myArray.length; // 3
myArray[0]; // "foo"
myArray[2]; // "bar"
Since they are objects, although not recommended, you can add properties to them withouth changing the array length:
var myArray = [ "foo", 42, "bar" ];
myArray.baz = "baz";
myArray.length; // 3
myArray.baz; // "baz"
DUPLICATING OBJECTS
For objects that are JSON-safe (can be serialized to JSON string and then back to JSON with same structure and values) you can use:
var newObj = JSON.parse( JSON.stringify( someObj ) );
In cases when you can't ensure JSON-safe, you can create a shallow copy (objects and functions assigned to properties are just references to these objects/functions):
var newObj = Object.assign( {}, myObject );
newObj.a; // 2
newObj.b === anotherObject; // true
newObj.c === anotherArray; // true
newObj.d === anotherFunction; // true
PROPERTY DESCRIPTORS
These are characteristics every object property has:
var myObject = {
a: 2
};
Object.getOwnPropertyDescriptor( myObject, "a" );
// {
// value: 2,
// writable: true,
// enumerable: true,
// configurable: true
// }
Those are the default values, but we can modify them (if it's configurable):
var myObject = {};
Object.defineProperty( myObject, "a", {
value: 2,
writable: true,
configurable: true,
enumerable: true
} );
myObject.a; // 2
There are 3 (excluding value) characteristics:
- WRITABLE
If you can change the value of a property
- CONFIGURABLE
If you can modify the propertie's descriptor definition, using again defineProperty(..). If a property is not configurable, you can still change writable from true to false, but not from false to true. It also prevents from using the delete operator on the property.
- ENUMERABLE
If a property will show up in certain object-property enumerations, like for..in loop.
IMMUTABILITY
To make properties or objects that cannot be changed. All of these approaches create shallow immutability, menaing they only affect the object and direct properties. If any object has a reference to another object (array, object, function, etc.) the contests of that object remain mutable.
- OBJECT CONSTANT
Combine writable:false and configurable:false. It creates a constant (cannot be changed, redefined or deleted).
var myObject = {};
Object.defineProperty( myObject, "FAVORITE_NUMBER", {
value: 42,
writable: false,
configurable: false
} );
- PREVENT EXTENSIONS
Prevents an object from having new properties added to it, but leaves the rest of the properties alone.
var myObject = {
a: 2
};
Object.preventExtensions( myObject );
myObject.b = 3;
myObject.b; // undefined
- SEAL
Object.seal(..) esentially calls Object.preventExtensions(..) but also marks all existing properties as configurable:false. So you cannot add more properties, and also cannot reconfigure or delete existing properties. But you can modify their values.
- FREEZE
Object.freeze(..) esentially calls Object.seal(..) but also marks all properties as writable:false.
[[GET]]
When you access an object property, it doesn't just look in the object for the property. It actually performs a [[Get]] operation (like a function call). This function first inspects the object for the property name and if it can find it it returns the value, if not the [[Get]] algorithm defines other important behavior and returns undefined (as opossed to a variable that cannot be resolved, where ReferenceError is thrown).
var myObject = {
a: 2
};
myObject.b; // undefined
[[PUT]]
How this operation behaves differs based on a number of factors, mainly if the property is already present or not.
If already present:
1) Is the property an accessor descriptor (see below)? Then call the setter.
2) Is the property a data descriptor with writable:false? Then silently fail in non-strict-mode, or throw TypeError in strict-mode.
3) Otherwise, set the value of the property as normal.
GETTERS & SETTERS
ES5 introduces a way to override part of the default operations of [[Get]] and [[Put]] at a per-property level. When a property has a getter and/or setter, the definition becomes an accessor descriptor (as opposed to data descriptor). For accesor descriptors JS ignores the value and writable characteristics, and considers set, get, configurable and enumerable.
var myObject = {
// define a getter for `a`
get a() {
return 2;
}
};
Object.defineProperty(
myObject, // target
"b", // property name
{ // descriptor
// define a getter for `b`
get: function(){ return this.a * 2 },
// make sure `b` shows up as an object property
enumerable: true
}
);
myObject.a; // 2
myObject.b; // 4
myObject.a = 3;
myObject.a; // 2
Thus creating a property on the object that doesn't actually hold a value, but whose access automatically results in a hidden function call. And even if we try to set a value for 'a' later or there's a valid setter, the custom getter is hard-coded to return 2.
It's recommended to always define both a getter and a setter:
var myObject = {
// define a getter for `a`
get a() {
return this._a_;
},
// define a setter for `a`
set a(val) {
this._a_ = val * 2;
}
};
myObject.a = 2;
myObject.a; // 4
EXISTENCE
You can ask an object if it has a certain property without asking to get that property's value:
var myObject = {
a: 2
};
("a" in myObject); // true
("b" in myObject); // false
myObject.hasOwnProperty( "a" ); // true
myObject.hasOwnProperty( "b" ); // false
The in operator checks if the property is in the object, or if it exists at any higher level of the [[Prototype]] chain. hasOwnProperty(..) only checks if the object has the property or not.
hasOwnProperty(..) is accessible via delegation to Object.prototype. But it is possible to create an object that doesn't link to Object.prototype. So there's a more robust way to check this:
Object.prototype.hasOwnProperty.call(myObject,"a")
ENUMERATION
There are properties that exists but they won't show up in some loops (for..in) or operations. That's because enumerable basically means "will be included if the object's properties are iterated through".
var myObject = { };
Object.defineProperty(
myObject,
"a",
// make `a` enumerable, as normal
{ enumerable: true, value: 2 }
);
Object.defineProperty(
myObject,
"b",
// make `b` NON-enumerable
{ enumerable: false, value: 3 }
);
myObject.b; // 3
("b" in myObject); // true
myObject.hasOwnProperty( "b" ); // true
// .......
for (var k in myObject) {
console.log( k, myObject[k] );
}
// "a" 2
myObject.propertyIsEnumerable( "a" ); // true
myObject.propertyIsEnumerable( "b" ); // false
Object.keys( myObject ); // ["a"]
Object.getOwnPropertyNames( myObject ); // ["a", "b"]
Object.keys(..) returns an array of all enumerable properties, whereas Object.getOwnPropertyNames(..) returns an array of all properties. Both inspect only the dirct object specified, not references to other objects it may include.
ITERATION
The for..in loop iterates over the enumerable properties of an object. And the standard for loop iterates over the indices of an array.
ES5 adds several iteration helpers for arrays:
- forEach(..)
Iterates over all the values and ignores any callback return values.
- every(..)
Keeps going until the end or the callback returns a false value.
- some(..)
Keeps going until the end or the callback returns a true value.
But if you want to iterate over the values directly of the array indices (or object properties), ES6 adds a for..of loop:
var myArray = [ 1, 2, 3 ];
for (var v of myArray) {
console.log( v );
}
// 1
// 2
// 3
The for..of loop asks for an iterator object of the thing to be iterated, and the loop then iterates over the successive return values from calling that iterator object's next() method, once for each loop iteration.
Arrays have a built-in @@iterator, so for..of works easily on them. Manually this looks like:
var myArray = [ 1, 2, 3 ];
var it = myArray[Symbol.iterator]();
it.next(); // { value:1, done:false }
it.next(); // { value:2, done:false }
it.next(); // { value:3, done:false }
it.next(); // { done:true }
We get at the @@iterator internal property of an object using ES6 Symbol: Symbol.iterator. Also @@iterator is not the iterator object itself, but a function that returns the iterator object. Note you have to call the next() a fourth time to know you are truly done iterating.
While arrays have a built-in @@iterator, regular objects do not. But it is possible to define your own @@iterator for any object:
var myObject = {
a: 2,
b: 3
};
Object.defineProperty( myObject, Symbol.iterator, {
enumerable: false,
writable: false,
configurable: true,
value: function() {
var o = this;
var idx = 0;
var ks = Object.keys( o );
return {
next: function() {
return {
value: o[ks[idx++]],
done: (idx > ks.length)
};
}
};
}
} );
// iterate `myObject` manually
var it = myObject[Symbol.iterator]();
it.next(); // { value:2, done:false }
it.next(); // { value:3, done:false }
it.next(); // { value:undefined, done:true }
// iterate `myObject` with `for..of`
for (var v of myObject) {
console.log( v );
}
// 2
// 3
Each time the for..of loop calls next() on the iterator's object, the internal pointer will advance and return the next value. This was a simple value by value iteration, but you can define complex iterations. For example an "infinite" iterator that returns a random number, an incremented value or a unique ID (make sure to limit the "infinite" iterator so it doesn't hang your program).
var randoms = {
[Symbol.iterator]: function() {
return {
next: function() {
return { value: Math.random() };
}
};
}
};
var randoms_pool = [];
for (var n of randoms) {
randoms_pool.push( n );
// don't proceed unbounded!
if (randoms_pool.length === 100) break;
}
----------------------------------------------------------------------------------------------------------------------------------------------
CLASSES
Classes are just one of several common design patterns (functional, OO, procedural, etc.). Classes don't map very naturally to JS, JS doesn't have classes, but with some effort you can implement approximations for much of class functionality.
Class/inheritance is a certain form of code organization and architecutre, it implies you classify a certain data structure, thinking about any given structure as a specific variation of a more general base definition.
Object Oriented or Class Oriented programming stresses that data intrinsically has associated behavior, so you package up the data and the behavior together.
Classes have mechanics such as:
INSTANTIATION
Think of the blue-print/building example, a class is a blue-print and to actually get an object to interact with, you build (aka instantiate) something from the class, the end result is an object/instance of the class. This object is a copy of all the characteristics described by the class.
Instances of classes are constructed by a special method of the class, usually of the same name as the class, called a constructor. It initializes any information (state) the instance will need.
//pseudo-code
class CoolGuy {
specialTrick = nothing
CoolGuy( trick ) {
specialTrick = trick
}
showOff() {
output( "Here's my trick: ", specialTrick )
}
}
Joe = new CoolGuy( "jumping rope" ) //the new keyword indicates the language we want to construct a new instance, calling the constructor
Joe.showOff() // Here's my trick: jumping rope
INHERITANCE
You can define another class (child) that inherits from the first class (parent).
Once the child class is defined, it's separate and distinct from the parent class. The child class contains an inital copy of the behavior from the parent but it can override any inherited behavior and define new behaviors.
//pseudo-code
class Vehicle {
engines = 1
ignition() {
output( "Turning on my engine." )
}
drive() {
ignition()
output( "Steering and moving forward!" )
}
}
class Car inherits Vehicle {
wheels = 4 //Defines new wheels data
drive() { //Overrides default drive()
inherited:drive() //References the original pre-override drive()
output( "Rolling on all ", wheels, " wheels!" )
}
}
class SpeedBoat inherits Vehicle {
engines = 2 //Overrides default engines
ignition() { //Overrides default ignition()
output( "Turning on my ", engines, " engines." )
}
pilot() { //Defines new pilot() behavior
inherited:drive() //References original pre-override drive()
output( "Speeding through the water with ease!" )
}
}
POLYMORPHISM
A class can define it's own method of the same name as the method from the class it inherits and it can also reference the original pre-overriden method.
Any method can reference another method (of the same or different name) at a higher level of inheritance hierarchy.
In many traditional class-oriented languages, the keyword 'super' is used to reference the class inherited from. The child class only gets a copy of what it needs from the parent, but both the original and overridden versions of that method are maintained.
Super also gives us a direct way for the constructor of a child class to reference the constructor of it's parent class. This is because with real classes the constructor belongs to he class, however, in JS it's more like the class belongs to the constructor.
In the example above, the SpeedBoat class references the inherited version of drive() but Vehicle's drive() references ignition(). So it will use the SpeedBoat version of ignition(). If you were to instantiate Vehicle class and then call it's method drive(), then it would use Vehicle's ignition().
MIXINS
JS object mechanism doesn't perform copies when you inherit or instantiate. Objects don't get copied to other objects, they get linked together. There are no classes in JS to instantiate, but JS developers fake the copy behavior of classes.
EXPLICIT MIXINS
Since JS will not copy behavior from one class to another, we can instead create a utility that manually copies. This is often called extend(..) by many libraries/frameworks.
// vastly simplified `mixin(..)` example:
function mixin( sourceObj, targetObj ) {
for (var key in sourceObj) {
// only copy if not already present
if (!(key in targetObj)) {
targetObj[key] = sourceObj[key];
}
}
return targetObj;
}
var Vehicle = {
engines: 1,
ignition: function() {
console.log( "Turning on my engine." );
},
drive: function() {
this.ignition();
console.log( "Steering and moving forward!" );
}
};
var Car = mixin( Vehicle, {
wheels: 4,
drive: function() {
Vehicle.drive.call( this );
console.log( "Rolling on all " + this.wheels + " wheels!" );
}
} );
Car now has a copy of the properties and references to the functions from Vehicles. So now, Car has a property called ignition, which is a copied reference to the ignition() function, as well as a property engines with a value of 1. Car already had a drive property so that reference wasn't overridden.
JS doesn't have a way to reference a property from the inheritance hierarchy. So we explicitly call the drive() frunction from the Vehicle object, but if we said Vehicle.drive() the 'this' binding would be the Vehicle object. Instead, we explicitly use .call(this) to ensure that it's executed in the context of the Car object.
As a result, Car will opearte somewhat separately from Vehicle. If you add a property onto Car, it will not affect Vehicle, and vice versa, unless the two objects share a reference to an object. Meaning this manual copying (mixins) doesn't actually emulate real copies from class-oriented languages.
PARASITIC INHERITANCE
A popular variation of this explicit mixin.
// "Traditional JS Class" `Vehicle`
function Vehicle() {
this.engines = 1;
}
Vehicle.prototype.ignition = function() {
console.log( "Turning on my engine." );
};
Vehicle.prototype.drive = function() {
this.ignition();
console.log( "Steering and moving forward!" );
};
// "Parasitic Class" `Car`
function Car() {
// first, `car` is a `Vehicle`
var car = new Vehicle();
// now, let's modify our `car` to specialize it
car.wheels = 4;
// save a privileged reference to `Vehicle::drive()`
var vehDrive = car.drive;
// override `Vehicle::drive()`
car.drive = function() {
vehDrive.call( this );
console.log( "Rolling on all " + this.wheels + " wheels!" );
};
return car;
}
var myCar = new Car();
myCar.drive();
// Turning on my engine.
// Steering and moving forward!
// Rolling on all 4 wheels!
IMPLICIT MIXINS
It's related to the explicit polymorphism call in the explicit mixin.
var Something = {
cool: function() {
this.greeting = "Hello World";
this.count = this.count ? this.count + 1 : 1;
}
};
Something.cool();
Something.greeting; // "Hello World"
Something.count; // 1
var Another = {
cool: function() {
// implicit mixin of `Something` to `Another`
Something.cool.call( this );
}
};
Another.cool();
Another.greeting; // "Hello World"
Another.count; // 1 (not shared state with `Something`)
We esentially call the function Something.cool() in the context of Another (via it's 'this' binding).
Usually you'll want to avoid mixins to keep cleaner and more maintainable code. Mixins circumvent the [[Prototype]] chain mechanism.
----------------------------------------------------------------------------------------------------------------------------------------------
PROTOTYPES
[[PROTOTYPE]]
Objects in JS are given, at the time of their creation, an internal property called [[Prototype]], which is a reference to another object.
When we invoke [[Get]] to reference a property on an object (e.g. myObject.a) that isnt't present on the object directly, the [[Get]] operation proceeds to follow the [[Prototype]] link of the object.
var anotherObject = {
a: 2