-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclass.js
More file actions
124 lines (94 loc) · 2.37 KB
/
class.js
File metadata and controls
124 lines (94 loc) · 2.37 KB
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
class User {
constructor(name) { this.name = name; }
sayHi() { console.log(this.name); }
}
const jack = new User.prototype.constructor('Jack'); // same as 'new User('Jack')'
console.log(jack); // User { name: 'Jack' }
// class is a function:
console.log(typeof User); // function
// ... more precisely a constructor method:
console.log(User === User.prototype.constructor); // true
// methods are in User.prototype:
console.log(User.prototype.sayHi); // [Function: sayHi]
// ...there are two methods:
console.log(Object.getOwnPropertyNames(User.prototype)); // [ 'constructor', 'sayHi' ]
// Class is not just a syntactic sugar
// class User rewritten in pure functions:
function User2(name) {
this.name = name;
}
User2.prototype.greet = function () {
console.log('Hello,', this.name);
}
const tom = new User2('Tom');
tom.greet(); // Hello, Tom
for (let prop in jack) {
console.log(`${prop}: ${jack[prop]}`); // name: Jack
}
for (let prop in tom) {
console.log(prop); // name, greet
}
// If a class expression has a name, it’s visible only inside the class:
const User3 = class MyClass {
msg() {
console.log(MyClass);
}
}
new User3().msg(); // [Function: MyClass]
// console.log(MyClass); <- error
// we can create a class dynamically:
function createClass(text) {
return class {
log() {
return console.log(text);
}
}
}
const myClass = createClass('Hello dynamical class');
new myClass().log(); // Hello dynamical class
// Getters and setters in a class:
class User4 {
constructor(name) {
this._name = name;
}
get name() {
return console.log(this._name);
}
set name(str) {
if (str.length < 3) {
return console.log('The name is too short.');
}
this._name = str;
}
}
const usr4 = new User4('Harry');
usr4.name; // Harry
usr4.name = 'George';
usr4.name; // George
// Using computed property in a getter and setter:
const ch = 'change';
const sh = 'show';
const nm = 'Name';
const obj = {
first: 'Bill',
get [sh + nm]() {
console.log(this.first);
},
set [ch + nm](value) {
this.first = value;
}
}
obj.first = 'Chris';
console.log(obj.first); // Chris
obj.changeName = 'William';
obj.showName; // William
// TASK:
class Clock {
constructor() {
let tick = 0;
setInterval(() => {
console.log(tick++);
}, 1000);
}
}
// const clock = new Clock(); // 0 1 2 3 4 ...