- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass.js
More file actions
Latest commit
123 lines (105 loc) · 2.76 KB
/
Copy pathclass.js
File metadata and controls
123 lines (105 loc) · 2.76 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
'use strict';
// Object-oriendted programming
// class: template
// object: instance of a class
// JavaScript classes
// - introduced in ES6
// - syntactical sugar over prototype-based inheritance
// 1. Class declarations
classPerson{
// constructior
constructor(name,age){
// fields
this.name=name;
this.age=age;
}
// methods
speak(){
console.log(`${this.name}: hello!`);
}
}
constsill=newPerson('sill',20);
console.log(sill.name);
console.log(sill.age);
sill.speak();
// 2. Getter and setter
classUser{
constructor(firstName,lastName,age){
this.firstName=firstName;
this.lastName=lastName;
this.age=age;
}
getage(){
returnthis._age;
}
setage(value){
// if(value < 0) {
// throw Error('age can not be negative');
// }
this._age=value<0 ? 0 : value;
}
}
constuser1=newUser('Steve','Job',-1);
console.log(user1.age);
// 3. Fields (public, private)
// Too soon!
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields
classExperiment{
publicField=2;
#privateField =0;
}
constexperiment=newExperiment();
console.log(experiment.publicField);
console.log(experiment.privateField);
// 4. Static properties and methods
// Too soon!
classArticle{
staticpublisher='Dream Coding';
constructor(articleNumber){
this.articleNumber=articleNumber;
}
staticprintPublisher(){
console.log(Article.publisher);
}
}
constarticle1=newArticle(1);
constarticle2=newArticle(2);
console.log(Article.publisher);
Article.printPublisher();
// 5. Inheritance
// a way for one class to extend another class.
classShape{
constructor(width,height,color){
this.width=width;
this.height=height;
this.color=color;
}
draw(){
console.log(`drawing ${this.color} color of`);
}
getArea(){
returnthis.width*this.height;
}
}
classRectangleextendsShape{}
classTriangleextendsShape{
draw(){
super.draw();// 부모에 사용된 draw 메소드도 호출!
console.log('triangle!');
}
getArea(){
return(this.width*this.height)/2;
}
}
constrectangle=newRectangle(20,20,'blue');
rectangle.draw();
console.log(rectangle.getArea());
consttriangle=newTriangle(20,20,'red');
triangle.draw();
console.log(triangle.getArea());
// 6. Class checking: instanceOf
console.log(rectangleinstanceofRectangle);// true
console.log(triangleinstanceofRectangle);// false
console.log(triangleinstanceofTriangle);// true
console.log(triangleinstanceofShape);// true
console.log(triangleinstanceofObject);// true