-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathThe Principles of OO JS
2007 lines (1637 loc) · 66.9 KB
/
The Principles of OO JS
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
Chapter One: Primitive and Reference Types
Lack of classes ->
Lack of packages (class grouping) ->
High degrees freedom of organization
Almost all data in JavaScript is an object OR is accessed via objects
Functions are represented as objects too - first class Functions
Objects can be created anytime
Object properties can be added or removed anytime
Two primary JavaScript data types:
1. primitive types
2. reference types
What are Types:
Primitive types: stored as simple data types
Reference types: stored as objects (references to location in memory)
Primitive types can be treated like reference types
JavaScript tracks variables for a particular scope with a "variable object"
- Primitive values are stored directly on the variable object
- Reference values are stored as pointers to location in memory in the variable object
Primitive Types:
Boolean: true or false
Number: any integer or floating numeric value
String: single or sequence of characters delimited by either single or double quotes - no character type
Null: a primitive type with only one value null
Undefined: default value of a variable; a primitive type with only one value, undefined
All primitive types have literal representation of their values
Literals are values NOT stored in a variable
A variable assigned with primitive value has its own copy of data
Identifying Primitive Types:
Best way to identify primitive types is with typeof operator
console.log(typeof "Charles"); // "string"
console.log(typeof 10); // "number"
console.log(typeof 10.1); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
EXCEPTION: null
console.log(typeof null); // "object"
The best way to identify null is by ===
console.log(value === null); // return true if value is null
Primitive Methods:
Despite having method, primitive values are NOT objects
null & undefined have no Methods
string:
var str = "TokenOne";
var lowercaseName = str.toLowerCase(); // "tokenone"
var firstLetter = str.charAt(0); // "T"
var middleStr = str.substring(2, 5); // "ken" (index: 2 - 4)
number:
var count = 10;
var fixedCount = count.toFixed(2); // convert to "10.00"
var hexCount = count.toString(16); // convert to "a", hexdecimal - base 16
boolean:
var flag = true;
var strFlg = flag.toString(); // convert to "true"
Reference Types:
Reference type represents objects
Reference values are instances / objects
Object is an unordered list of properties (name : value pairs)
If a property's value is function, the property is a "method"
Function is reference value
Creating Objects:
new operator with a constructor
- constructor is any function that uses new to create an object
- constructor begin with a capital letter by convention
Ex. var object = new Object();
- When an object is assigned to a varaiable, only the reference / pointer is copied,
the memory referenced by the pointer is shared among variables
Ex.
var obj01 = new Object();
var obj02 = obj01;
Dereferencing Objects:
JavaScript is a garbage-collected language
Deference a reference by assign the variable to null
Adding or Removing Properties
Ex.
var object1 = new Object();
var object2 = object1;
object1.myProperty = "Awsome!";
console.log(object2.myProperty); // "Awsome!"
Instantiating Built-In Types:
Built-In types:
Array - an ordered list of numerically indexed values
Date - a date and time
Error - a runtime error (with several more specific subtypes)
Function - a function
Object - a generaic object
RegExp - a regular expression
Instantiation:
var list = new Array();
var now = new Date();
var error = new Error("Somthing Wrong");
var func = new Function("console.log('log')");
var object = new Object();
var re = new RegExp("\\d+");
Literal Forms
Literal:
syntax that define a reference value
without explicitly creating an object using "new" operator and constructor
Object and Array Literals
object literal syntax:
define properties of a new object inside braces
but does NOT call the constructor
property is made of:
1. identifier or string
2. colon
3. value
Multiple properties are separated by commas
Ex. with identifier as property name
var book = {
name: "The Principles of Object-Oriented JavaScript",
year: 2014
}
Ex. same object with string literals as property name
var book = {
"name": "The Principles of Object-Oriented JavaScript",
"year": 2014
}
Logically Equvilent to
var book = new Object();
book.name = "The Principles of Object-Oriented JavaScript";
book.year = 2014;
Array literal:
Ex.
var colors = [ "red", "white", "blue"];
Logically Equvilent to
var colors = new Array("red", "white", "blue");
Function Literals
Define function with constructor is discouraged
Define function with literal form is preferred
Ex. literal form
function reflect(value) {
return value;
}
Ex. same function defined by constructor - but hard to debug
var reflect = new function ("value", "return value;");
Regular Expression Literals
The pattern is contained b/t two forward slashes (/)
Additional options are single characters follow the second forware slash
Ex. literal form - preferred when constructed dynamically
var numbers = /\d+/g; // a little easier - no need to escape characters, \d+
Ex. Identical constructor form
var numbers = new RegExp("\\d+", "g"); // need to escape backslashes, \\d+
Property Access
By dot notation:
Ex.
var array = [];
array.push(12345);
By bracket notation:
Ex.
var array = [];
array["push"](12345);
Bracket notation can be used to call method dynamically
Bracket notation allow use of special characters in property name
Dot notation is more readable for most
Identifying Reference Types
Function is identified via typeof operator
Ex.
function reflect(value) {
return value;
}
console.log(typeof reflect); //"function"
For all other reference types, keyword typeof returns "object"
Use "instanceof" to identify these objects
Ex. instanceof
var items = [];
var object = {};
function reflect(reflect) {
return value;
}
console.log(items instanceof Array); // return true
console.log(object instanceof Object); // return true
console.log(reflect instanceof Function); // return true
Use "instanceof" to identify inherited types
Ex.
var items = [];
var object = {};
function reflect(value) {
return value;
}
console.log(items instanceof Array);
console.log(items instanceof Object);
console.log(object instanceof Object);
console.log(object instanceof Array); // false
console.log(reflect instanceof Function);
console.log(reflect instanceof Object);
Identifying Arrays
keyword instanceof can identify array
Each web page has its own global context
- its own version of Object, Array and all builtin types
Array from one frame cannot be identify by instanceof
ES 5 feature: Array.isArray() - Not supported in IE 8 or eariler
Ex.
var items = [];
console.log(Array.isArray(items)); // true
Primitive Wrapper Types
references types exist to make primitive types works like object
String
Number
Boolean
Ex. String.charAt()
var name = "Charles";
var firstChar = name.charAt(0);
console.log(firstChar); // "N"
Actual implementation:
var name = "Charles";
var temp = new String(name); // "Autoboxing": implicit creation of wrapper type
var firstChar = name.charAt(0);
temp = null; // "Autoboxing": implicit removeal of wrapper type right after wrapper method call
console.log(firstChar); // "N"
Due to automboxing, Wrapper Types can NOT be used like noraml reference types
Ex. Additional properties wrapper type CANNOT be accessed
var name = "Charles";
name.last= "Kuo";
console.log(name.last); // undefined
Actucal implementation
var name = "Charles";
var temp = new String(name);
name.last= "Kuo";
temp = null;
var temp = new String(name); // wrapper type created
console.log(temp.last); // undefined
temp = null;
Primitive types cannot be identified as its wrapper types by keyword instanceof
Ex.
var name = "Charles";
console.log(name instanceof String); // false
Wrapper types cannot be used as its primitive types
Ex.
var found = new Boolean(false);
if (found) { console.log("Found"); } // found is truthy
Avoid instantiating primitive wrappers manually
Summary
JS: types, not class
primitive types: string, number, boolean, null, undefined
all primitive types but "null" can be identified by keyword typeof
identify "null" by === compare with "null"
Functions are identified by typeof operator
primitive wrapper types: String, Number, Boolean
Chapter Two: Functions
Functions are distinguished from other objects by its internal property [[Call]]
Internal property cannot be accessed by code
Functions are identified via "typeof" keyword
Declarations vs. Expression
Function Declaration:
1. "function" keyword
2. function name
3. zero or more parameters enclosed in parenthese, saperated by commas
4. content enclosed in braces
Ex.
function add(num1, num2) {
return num1 + num2;
}
Function declarations are hoisted to the top of context
Ex.
var result = add(5, 5);
function add(num1, num2) {
return num1 + num2;
}
... is actually interpreted by JS engine
function add(num1, num2) {
return num1 + num2;
}
var result = add(5, 5);
Function Expression:
1. "function" keyword
2. zero or more parameters enclosed in parenthese, saperated by commas
3. content enclosed in braces
Function Expression(s) are anonymous
- usually assigned to a variable or property & ends with semicolon
Ex.
var add = function(num1, num2) {
return num1 + num2;
};
Define functions before usage to avoid potential issues
Function as values
Functions can be used like other objects, such as:
- assigned to variables
- added to objects
- passed as arguments to other functions
- returned from other functions
Ex. assign function to variables
function sayHi() {
console.log("Hi!");
}
sayHi(); // outputs "Hi!"
var sayHi2 = sayHi;
sayHi2(); // outputs "Hi!"
Ex. pass function as arguments to other functions
var numbers = [ 1, 5, 8, 4, 7, 10, 2, 6 ];
numbers.sort(function(first, second) {
return first - second;
});
console.log(numbers); // "[1, 2, 4, 5, 6, 7, 8, 10]"
numbers.sort();
console.log(numbers); // "[1, 10, 2, 4, 5, 6, 7, 8]"
Comparison function (as function expression & anonymous function) is passed into sort()
numbers.sort(); sorts array as strings
Parameters
JS function takes any number of parameters without causing error
"arguments" property of function object:
automatically available within any function
store parameters
reference parameter by numeric index
"length" property determines (arity) number of expected parameters
BUT "arguments" is NOT an array -> Array.isArray(arguments) always return false
Ex.
// function declaration
function reflect(value) {
return value;
}
console.log(reflect("Hi")); // "Hi" - first argument only
console.log(reflect("Hi", 25)); // "Hi" - first argument only
console.log(reflect.length); // 1 - one named parameter
// function expression
function = function() {
return arguments[0];
};
console.log(reflect("Hi")); // "Hi" - first argument only
console.log(reflect("Hi", 25)); // "Hi" - first argument only
console.log(reflect.length); // 0 - no named parameter
"arguments" is best used when expecting no-fixing number of parameters
Ex. function sum() {
var result = 0,
i = 0,
len = arguments.length;
while (i < len) {
result += arguments[i];
i++;
}
return result;
}
console.log(sum(1, 2)); // 3
console.log(sum()); // 0 - reusult is initialized with zero
Overloading
Function overloading is NOT available b/c same function can accept multiple parameters
Mimic function overloading by arguments object
Ex.
function sayMessage(message) {
// alternatively: if (message === undefined)
if (arguments.length === 0) {
message = "Default message";
}
console.log(message); // when function is called with at least one parameter
}
Use "typeof" or "instanceof" to check for diffeent data type
Object Methods
When object property is a function, the property is considered as method
Method can be added like property with the same syntax
Ex.
var person = {
name: "Charles",
sayName: function() {
console.log(person.name);
}
};
person.sayName(); // outputs: "Charles"
The "this" Object
"this" object represents the calling object for the function
In global scope, "this" represents global object
In web browser, the global object is "window"
When function is called while attached to an object, "this" represents the object
Ex.
var person = {
name: "Charles",
sayName: function() {
console.log(this.name); // access object property dynamically for code reuse
}
};
person.sayName(); // outputs: "Charles"
Ex.
function sayNameForAll() {
console.log(this.name);
}
var person1 = {
name: "Jack",
sayName: sayNameForAll
};
var person2 = {
name: "Charles",
sayName: sayNameForAll
};
var name = "Old Sport"; // global varaiable
person1.sayName(); // "Jack"
person2.sayName(); // "Charles"
sayNameForAll(); // "Old Sport" - global variable is property of global object
Changing this
call() method:
1st parameter: the value to which "this" should be equal when the function is executed
subsequent parameters will be passed into the function
Ex.
function sayNameForAll(label) {
console.log(label + ":" + this.name);
}
var p1 = {name: "Charles"};
var p2 = {name: "Jack"};
var name = "Old Sport";
sayNameForAll.call(this, "global"); // output "global: Old Sport"
sayNameForAll.call(p1, "person1"); // output "person1: Charles"
sayNameForAll.call(p2, "person2"); // output "person2: Jack"
apply() method:
1st parameter: the value to which "this" should be equal when the function is executed
subsequent parameters will be passed into the function AS ARRAY
Ex.
function sayNameForAll(label) {
console.log(label + ":" + this.name);
}
var p1 = {name: "Charles"};
var p2 = {name: "Jack"};
var name = "Old Sport";
sayNameForAll.apply(this, ["global"]); // output "global: Old Sport"
sayNameForAll.apply(p1, ["person1"]); // output "person1: Charles"
sayNameForAll.apply(p2, ["person2"]); // output "person2: Jack"
bind() method:
This function is added after ES5; return a new function bind to a given object
1st parameter: "this" value for the new function
subsequent parameters will be passed into the function
Ex.
function sayNameForAll(label) {
console.log(label + ":" + this.name);
}
var p1 = {name: "Charles"};
var p2 = {name: "Jack"};
// create a function just for p1
var sayNameForPerson1 = sayNameForAll.bind(p1);
sayNameForPerson1("person1"); // outputs "person1:Charles"
// create a function just for p2
var sayNameForPerson2 = sayNameForAll.bind(p2);
sayNameForPerson2("person2"); // outputs "person2:Jack"
// attaching a method to an object does not change "this"
p2.sayName = sayNameForPerson1;
p2.sayName("person2"); // outputs "person2:Charles"
Summary
Functions are objects too
Function has special internal property [[Call]]
Function declaration
- function name is right of the "function" keyword
- Hoisted to top of the context scope
Function expression
- other values can also be used
Function constructor should be avoided
Chapter Three: Primitive and Reference Types
JS objects are dynamic - can change during execution
Defining Properties
Objects (properties) created by programmer are always open for modification unless specified otherwise
When property first added to object,
- Internal method [[Put]] specifies initial value & attributes of the property
- By creating an "own property" on object
- "Own property" indicate a specific instance of object owns that property
- All operations on the propery must be performed via its object
- "Own property" are different from prototype properties
When new value assigned to an existing property:
- Internal method [[Set]] replace old value with new
Ex.
var person1 = { name: "Charles" }; // [[Put]]name
person1.age = "Redacted"; // [[Put]]age
person1.name = "Greg"; // [[Set]]name
Detecting Properties
Avoid checking property existence by "truthy" or "falsy" value (in if expression)
- a valid property can contain falsy values -> causing false negative
truthy:
- an object
- non-empty string
- non-zero number
- true
falsy:
- null
- undefined
- 0
- NaN
- empty string
Detect property existence with "in" operator:
"in" operator checks for given key exists in hash table
Ex. ... following previous example
console.log("name" in person1); // "true" - person1 holds property "name"
console.log("age" in person1); // "true" - person1 holds property "age"
console.log("title" in person1); // "false"- No "title" property in person1
Detect method (function as property) with "in" operator
Ex.
var person1 = {
name: "Charles",
sayName: function() {
console.log(this.name);
}
};
console.log("sayName" in person1); // true
Detect property with "in" will NOT evaluate value of property
- this avoid error or performance issue
- detect own properties AND prototype properties
Detect ONLY own properties with hasOwnProperty() method
Ex. following example above
console.log("toString" in person1); // true
console.log(person1.hasOwnProperty("toString")); // false
// toString() method is a prototype present on all objects
Removing Properties
"delete" operator calls internal operator [[Delete]] to remove key/value pair from hash table
Upon successful delete, it returns true
Ex.
var person1 = {
name: "Charles"
};
console.log("name" in person1); // true
console.log(delete person1.name); // delete property & return true
console.log("name" in person1); // false
console.log(person1.name); // undefined
Enumeration
By default, all properties added are enumerable
Enumerable properties have internal [[Enumerable]] attributes set to true
Ex.
var obj = {a: 1, b: 2, c: 3};
var prop;
for (prop in obj) {
console.log('Name: ' + prop);
console.log('Value: ' + obj[prop]);
}
"for - in" loop return prototype & own properties
Object.keys(obj) retrive enumerable peoperties from object in parameter
Ex.
var obj = {a: 1, b: 2, c: 3};
var properties = Object.keys(obj);
// if you want to mimic for-in behavior
var i, len;
for (i=0, len=properties.length; i < len; i++){
console.log("Name: " + properties[i]);
console.log("Value: " + obj[properties[i]]);
}
Object.keys() returns ONLY own / instance properties
Not all properties are enumerable
- most native methods on object have [[Enumerable]] attribute set to false
- check whether a property is enumerable by propertyIsEnumerable()
Ex.
var person = {name: "Charles"};
console.log("name" in person); // true
console.log(person.propertyIsEnumerable("name")); // true
var properties = Object.keys(person);
console.log("length" in properties); // true
console.log(properties.propertyIsEnumerable("length")); // false - length is a built-in property on Array.prototype
Type of Properties
1. Data property: contains a value
- by default [[Put]] method creates data property
2. Accessor property:
- define a function to call when property is read (getter)
- define a function to call when property is written nto (setter)
- To add behavior for value assignment / read
- With only getter, property is read-only, write will fail silently in nonstrict mode and throw error in strict mode
- With only setter, property is write-only, read will fail silently in nonstrict and strict mode
Ex.
var person = {
_name: "Charles", // leading underscore is just convention, property is still public
get name() {
console.log("Reading name");
return this._name;
},
set name(value) {
console.log("Setting name to %s", value);
this._name = value;
}
};
console.log(person.name);
person.name = "Old Sport";
console.log(person.name);
Property Attributes
Common Attributes
[[Enumerable]]: determine if property can be iterated over
[[Configurable]]: determine if property can be changed
- configurable property attributes (other than value & writable) can be changed at any time
- configurable property can be remove with "delete"
- configurable property can be changed between data and accessor property
By default, user defined properties are Enumerable & Configurable
Change property attributes by Object.defineProperty() method
- three arguments
1. owning object
2. property name
3. property descriptor object containing attributes to set
- descriptor has properties of the same name as internal attribute but without square brackets
- use enumerable to set [[Enumerable]]
- use configurable to set [[Configurable]]
Ex. Make an object property non-enumerable & non-configurable
var p1 = {name: "Charles"}; // define name property
Object.defineProperty(p1, "name", {
enumerable: false
}); // modify name's [[Enumerable]] attribute to false
console.log("name" in p1); // true
console.log(p1.propertyIsEnumerable("name")); // false
var properties = Object.keys(p1);
console.log(properties.length); // 0
Object.defineProperty(p1, "name", {
configurable: false
}); // name is now non-configurable - the property CANNOT be changed, it is LOCKED down
delete p1.name; // try to delete property - will ERROR out in strict mode or fail silently in non-strict mode
console.log("name" in p1); // still true
console.log(p1.name); // still "Charles"
Object.defineProperty(p1, "name", {
configurable: true
}); // ERROR! Uncaught TypeError: Cannot redefine property: name
Switch between data property and accessor property will also produce error
Data Property Attributes
Data properties have two additional attributes that accessors do not:
[[Value]]: holds property value, filled automatically when property is created, include function
[[Writable]]: boolean value indicating weather property can be written to
- by default, all properties are writable, unless specified otherwise
Ex. Define a data property with Object.defineProperty
var p1 = {name: "Charles"}; // ...is logically equvilent to ...
var p1 = {};
Object.defineProperty(p1, "name", {
value: "Charles",
enumerable: true,
configurable: true,
writable: true
});
When Object.defineProperty() is called:
1. check if property exists
2. if property NOT exist, a new one is added per descriptor
When define property with Object.defineProperty(), any unspecified boolean attribute is default to false
Ex. Object.defineProperty() without specifying boolean attribute
var p1 = {};
Object.defineProperty(p1, "name", {
value: "Charles"
}); // only read property is possible; all else are locked down
console.log("name" in p1);
console.log(p1.propertyIsEnumerable("name")); // false - enumerable: false by default
delete p1.name;
console.log("name" in p1); // true - configurable: false by default when not specified in Object.defineProperty()
p1.name = "Jack";
console.log(p1.name); // "Charles" - writable: false by default when not specified in Object.defineProperty()
Non-writable property throws error when re-assigned in strict mode and fails silently when in nonstrict mode
Accessor Property Attributes
Accessor properties also have two additional attributes that data properties do not
[[Get]] for getter
[[Set]] for setter
Only one of the attributes is required to create an accessor property
Create a property with both data AND accessor attributes cause error
Ex. accessor with Object.defineProperty()
var p1 = { _name: "Charles" };
Object.defineProperty(p1, "name", {
get: function() {
console.log("Reading name");
return this._name;
},
set: function(value){
console.log("Setting name to %s", value);
this._name = value;
},
enumerable: true,
configurable: true
});
console.log(p1.name);
p1.name = "Jack";
console.log(p1.name);
"get" and "set" keys are passed in as data properties containing function
Setting attributes [[Enumerable]] and [[Configurable]] enables user
to identify and change how accessor property works.
Ex. Non-configurable, Non-enumerable, Non-writable property
var p1 = { _name: "Charles" };
Object.defineProperty(p1, "name", {
get:function(){
console.log("Reading name");
return this._name;
}
});
console.log("name" in p1); // true
console.log(p1.propertyIsEnumerable("name")); // false
delete p1.name;
console.log("name" in p1); // true
p1.name = "JackGreg";
console.log(p1.name); // "Charles"
Defining Multiple Properties
with Object.defineProperties()
- takes two arguments:
1. object to work on
2. object with all properties info
- property names
- values: descriptor objects defining attributes of the property
Ex. define data and accessor property
var p1 = {};
Object.defineProperties(p1, {
// data property
_name: {
value: "Charles",
enumerable: true,
configurable: true,
writable: true
},
// accessor property
name: {
get: function() {
console.log("Reading name");
return this._name;
},
set: function(value) {
console.log("Setting name to %s", value);
this._name = value;
},
enumerable: true,
configurable: true
}
});
console.log(p1.name);
p1.name = "Jack";
console.log(p1.name);
Retrieving Property Attributes
Object.getOwnPropertyDescriptor() takes 2 arguments:
1. object to work on
2. property to check
Ex.
var p1 = { name: "Charles" };
var descriptor = Object.getOwnPropertyDescriptor(p1, "name");
console.log(descriptor.enumerable); // true
console.log(descriptor.configurable); // true
console.log(descriptor.writable); // true
console.log(descriptor.value); // "Charles"
Preventing Object Modification
[[Extensible]]: boolean value that indicates if object can be modified
Extensible = new properties can be added to object at any time
Verify [[Extensible]] by Object.isExtensible()
Thre are 3 ways to prevent object modifications; all are irreversible
1. Preventing Extensions
Object.preventExtensions() takes 1 argument: object to make non-extensible
Ex.
var p1 = {name: "Charles"};
console.log(Object.isExtensible(p1)); // true
Object.preventExtensions(p1);
console.log(Object.isExtensible(p1)); // false
p1.sayName = function() {
console.log(this.name);
};
console.log("sayName" in p1); // false
2. Sealing Objects
Seal object makes it non-configurable and non-extensible
Sealed object can only be read from or write to its properties
Object.seal() takes 1 argument: object to be sealed
Seal status can be verified with Object.isSealed()
Sealed object cannot be un-sealed
Ex.
var p1 = { name: "Charles" }; // by default an object is NOT sealed and is extensible
console.log(Object.isExtensible(p1)); // true
console.log(Object.isSealed(p1)); // false
Object.seal(p1);
console.log(Object.isExtensible(p1)); // false
console.log(Object.isSealed(p1)); // true
// try to add a function as property to a sealed object, p1
p1.sayName = function() {
console.log(this.name);
};
// check if a sealed object can have new method
console.log("sayName" in p1); // false
// check if a sealed object can re-assign its property value
p1.name = "Jack";
console.log(p1.name); // "Jack"
// check if property of a sealed object can deleted
delete p1.name;
console.log("name" in p1); // true - still present
console.log(p1.name); // "Jack"
// check if property of a sealed object is configurable by Object.getOwnPropertyDescriptor()
var descriptor = Object.getOwnPropertyDescriptor(p1, "name");
console.log(descriptor.configurable); // false
Use strict mode with sealed object so error is thrown when object is used incorrectly
3. Freezing Objects
Object.freeze() takes one object to be frozen
A frozen object CANNOT:
- add or remove properties
- change property type
- be un-frozen
- re-assign data property
Forzen state is checked with Object.isFrozen()
Ex.
var p1 = { name: "Charles" }; // by default an object is NOT sealed and is extensible
console.log(Object.isExtensible(p1)); // true
console.log(Object.isSealed(p1)); // false
console.log(Object.isFrozen(p1)); // false
Object.freeze(p1);
console.log(Object.isExtensible(p1)); // false
console.log(Object.isSealed(p1)); // true
console.log(Object.isFrozen(p1)); // true
// try to add a function as property to a frozon object, p1
p1.sayName = function() {
console.log(this.name);
};
// check if a frozen object can have new method
console.log("sayName" in p1); // false
// check if a frozen object can re-assign its property value
p1.name = "Jack";
console.log(p1.name); // No, still "Charles"
// check if property of a frozen object can deleted
delete p1.name;
console.log("name" in p1); // true - still present
console.log(p1.name); // "Charles"
// check if property of a frozen object is configurable / writable by Object.getOwnPropertyDescriptor()
var descriptor = Object.getOwnPropertyDescriptor(p1, "name");
console.log(descriptor.configurable); // false
console.log(descriptor.writable); // false
Summary
obj.hasOwnProperty(prop)
- check for specific property (prop) as direct property of the object
prop in obj
- check for specific property (prop) as own property or from prototype chain
Object.keys(obj)
- return an arry of enumerable properties
Object.getOwnPropertyNames(obj)
- return an arry of enumerable and non-enumerable properties
- but item on prototype chain are NOT listed
Object.preventExtensions()
Object.isExtensible() / add property: false
Object.configurable() / delete property: true
(Descriptor) writable: true
Object.seal()
Object.isExtensible() / add property: false
Object.configurable() / delete property: false
(Descriptor) writable: true
Object.freeze()
Object.isExtensible() / add property: false
Object.configurable() / delete property: false
(Descriptor) writable: false
Chapter Four: Constructors And Prototypes
- not exactly like class
Constructors
constructor: a function used with "new" to create an object
Objects created with same constructor contain the same properties and methods
User defined constructor = user defined reference type
Ex.
function Person() {
// intentionally blank
}