JavaScript

드림코딩 : JS - 6. 객체 지향 class

식초 2020. 10. 16. 19:53
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
'use strict';
//객체 지향 프로그래밍
//class: template
//object: instance of a class
//자바스크립트 클래스
//-ES6에서 소개됨
//-기존 프로토타입에 기반해서 문법만 클래스 추가: syntactical sugar
 
 
 
//1. Class 선언
class Person {
    //constructor
    constructor(name, age){
        //fields
        this.name = name;
        this.age = age;
    }
    //methods
    speak(){
        console.log(`${this.name}: hello!`);
    }
}
 
const sigcho = new Person('sigcho'26); //new 붙여서 새로운 클래스 만든다
console.log(sigcho.name);  //sigcho
console.log(sigcho.age);  //26
sigcho.speak();  //sigcho: hello!
 
//2. Getter and setters
class User {
    constructor(firstName, lastName, age){
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }
    get age(){ //값 리턴, this.age 사용할 때 실행
        return this._age; //_age로 게터의 변수 이름 바꾼다
    }
    set age(value){ //값 설정, =age 사용할 때 실행
        //if(value < 0){
        //    throw Error('age can not be negative'); //경고를 준다
        //}
        this._age =value < 0 ? 0 : value;  //_age로 세터의 변수 이름 바꾼다 //0보다 작으면 0, 아니면 value값 준다
    }
}
 
const user1 = new User('Steve''Job'-1); //사람의 나이를 -1살로 잘못 설정함
console.log(user1.age); 
 
 
 
//3. Fields (public, private)
//To soon!
class Experiment {
    publicField =2//외부에서 접근 가능
    #privateField =0//클레스 내부에서만 rw가능
}
const experiment = new Experiment();
console.log(experiment.publicField); //2
console.log(experiment.privateField); //undefined
 
 
 
//4. Static properties and methods
//To soon!
//들어오는 데이터, object에 상관없이 공통적으로 class에서 쓸 수 있는 것이라면 static과 static method 이용
class Article {
    static publisher = 'Dream Coding';
    constructor(articleNumber){
        this.articleNumber = articleNumber;
    }
 
    static printPublisher(){
        console.log(Aticle.publisher);
    }
}
 
const article1 = new Article(1); 
const article2 = new Article(2); 
console.log(article1.publisher); //undefined, static은 객체가 아니라 클래스 자체에 붙어있다
console.log(Article.publisher); // Dream Coding 출력
Article.printPublisher(); //Dream Coding 출력
 
 
 
//5. Inheritance (상속)
//하나의 클래스가 또다른 클레스로 연장 extend
class Shape {
    constructor(width, height, color){
        this.width = width;
        this.height = height;
        this.color = color;
    }
    draw(){
        console.log(`drawing ${this.color} color of`); //여기서 한번 고치면 나머지도 다 고쳐진다
    }
    getArea(){
        return this.width * this.height;
    }
}
 
class Rectangle extends Shape {} //Shape의 fields와 methods가 자동으로 포함된다
class Triangle extends Shape {
    getArea(){
        draw(){
            super.draw(); //부모의 메소드 호출
            console.log('▲');  //새로운 메소드 정의
        }
        return (this.width * this.height) / 2//오버라이딩: 필요한 함수만 재정립
    }
}
 
const rectangle = new Rectangle(2020'blue');
rectangle.draw(); //drawing blue color of 호출됨
console.log(rectangle.getArea());
const triangle = new Triangle(2020, red);
triangle.draw(); //drawing read color of 호출됨
 
 
 
//6. Class checking: instanceOf (객체가 클래스의 상속인지 아닌지, true|false)
console.log(rectangle instanceof Rectangle); //true
console.log(triangle instanceof Rectangle); //false
console.log(triangle instanceof Triangle); //true
console.log(triangle instanceof Shape); //ture
console.log(triangle instanceof Object); //true, 자바스크립트의 모든 객체, 클래스는 object를 상속한 것이다
console.log(triangle.toString());//어떤 객체든지 공통적인 object의 메소드를 쓸 수 있다
 
cs

 

getter와 setter 오류