-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsummary-objects.js
68 lines (52 loc) · 2.06 KB
/
summary-objects.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
// The simplest way to create an object is using an object literal
const circle = {
radius: 1,
draw: function() {}
};
// To create multiple objects with the same structure and behaviuor (methods), use a factory or a constructor.
// Factory function
function createCircle(radius) {
return {
radius,
draw: function() {}
}
}
// Constructor function
function Circle(radius) {
this.radius = radius;
this.draw = function() {}
}
// Every object has a "constructor" property which returns the function that was used to construct or create that object.
const x = {};
x.constructor; // returns Object()
// In JavaScript, functions are objects. They have properties and methods.
Circle.name;
Circle.length;
Circle.constructor; // returns Function()
Circle.call({}, 1); // to call the Circle function
Circle.apply({}, [1]);
// Value types are copied by their value, reference types are copied by their reference.
// Value types in JavaScript are: String, Number, Boolean, Symbol, undefined and null
// Reference types are: Object, Function and Array
// JavaScript objects are dynamic. You can add/remove properties:
circle.location = {};
circle['location'] = {};
delete circle.location;
// To enumerate the members in an object:
for (let key in circle) console.log(key, circle[key]);
Object.keys(circle);
// To see if an object has a given property
if ('location' in circle)
// Abstraction means hiding the complexity/details and showing only the essentials.
// We can hide the details by using private members. Replace "this" with "let".
function Circle(radius) {
// Public member
this.radius = radius;
// Private member
let defaultLocation = {};
}
// To define a getter/setter, use Object.defineProperty():
Object.defineProperty(this, 'defaultLocation', {
get: function() { return defaultLocation; },
set: function(value) { defaultLocation = value; }
});