본문 바로가기
javascript/javascript 고급문법

[javascript] class

by 남민섭 2022. 11. 30.
728x90
반응형

class는 객체를 만들기 위한 도구, 템플릿

변수와 메소드를 정의하는 일종의 틀이다

객체를 정의하기위한 상태(멤버변수)와 메소드(함수)로 구성된다

 

예시 구문)

class Person {
	constructor(name, age, hasJob) {
		this.name = name;
		this.age = age;
		this.hasJob = hasJob;
	}
	speak() {
		console.log("hello");
	}
	eat() {
		console.log("먹는다");
	}
}


let person3 = new Person("aaa", 30, false);

 

1. new 키워드를 사용하여 생성자 호출/생성

2. 호출을 하면 constructor() 생성자 함수를 찾아서 값들을 초기화 및 할당

(공장에서 같거나 다른 기계들을 많이 뽑는다고 생각하면됨) / 붕어빵 만들때 틀

 


 

클래스 상속

  • extends 키워드를 사용한다
  • 정의된 클래스를 상속 받아서 새로운 클래스를 생성할 수 있음
  • 상속 받은 부모에 해당하는 클래스에 정의된 변수, 함수 등
    모든특성을 그대로 상속 받아 사용할 수 있음
  • 자식에 해당하는 클래스에서 추가적이 부분만 정의하면됨

 

오버라이딩

상속 관계에 있는 부모 클래스에서 이미 정의된 메소드를 자식 클래스에서 메소드로 다시 재정의하는것

(부모에 있는 메소드 내용을 수정?추가?)

 

super키워드

super를 이용하여 부모요소의 메소드 기능을 가져올 수 있다

 

 

예시 구문)

class Person {
	constructor(name, age, hasJob) {  //생성자 함수,초기화
		this.name = name;
		this.age = age;
		this.hasJob = hasJob;
	}
	speak() {
		console.log("hello");
	}
	eat() {
		console.log("먹는다");
	}
}

class childClass extends Person {
	speak(){  //오버라이딩
    	super.speak()  //부모클래스(Person) 기능을 가져옴
    	console.log("안녕")
    }
    
}


let person3 = new Person("aaa", 30, false);
childClass.speak()

//hello 
//안녕

 

1. new키워드를 사용하여 class 호출했으면 부모/자식class의 constructor 생성자 함수를 먼저 찾는다 

2. 메소드가 호출 됬을 경우 부모class보다 자식 class 에 호출한 메소드가 있는지 먼저 파악한다(자식class 에 메소드가 있으면 자식class 메소드 실행 없으면 부모 class 확인)

 


 

부모 class 기능을 상속받은 자식class에게 생성자함수를 입력하고싶거나

매개변수값을 추가로 넣고 싶을때

 

예시 구문)

class Person {
	constructor(name, age, hasJob) {  //생성자 함수,초기화
		this.name = name;
		this.age = age;
		this.hasJob = hasJob;
	}
	speak() {
		console.log("hello");
	}
	eat() {
		console.log("먹는다");
	}
}

class childClass extends Person {
	constructor(name, age, hasJob, height) {  //생성자 함수,초기화
		super(name, age, hasJob);  //부모class에서 기능 가져옴
        this.height = height;  //추가 변수값
	}
	speak(){  //오버라이딩
    	super.speak()  //부모클래스(Person) 기능을 가져옴
    	console.log("안녕")
    }
    
}


let person3 = new Person("aaa", 30, false, 180);  // 180 추가로 넣음

 


 

class 실습 1 

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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        class Student {    
            //student 클래스 선언
            constructor(name, score1, score2) { 
//constructor함수는 class로 생성된 객체를 생성하고 초기화하기 위한 특수함수
                this.name = name;  
                this.score1 = score1;  
                this.score2 = score2;  
            }
            sum() {  //sum()메소드
                return (this.score1 + this.score2);  
//score1 + score2 두 값을 더해서 되돌려줌
            }
        }
// 추가하거나 수정할게 생기면 extents기능 사용
        class ExtentionStudent extends Student {    
//student 클래스를 extends기능에 의해 ExtentionStudent에 상속시켜줌
            constructor(name, score1, score2, score3) {  
//constructor함수는 class로 생성된 객체를 생성하고 초기화하기 위한 특수함수 
(score3추가)
                super(name,score1, score2);      
//super 는 부모요소에 있는 변수를 호출하기위해 사용함  //내용 추가및 수정은 오버라이딩 
                this.score3 = score3;    //추가변수        
            }
            total() {    //total이라는 메소드 선언
                return(super.sum() + this.score3);  
//sum()메서드 부모요소에서 기능을 받아오고 score3와 더해서 되돌려준다
            }
        }

/////////////////////////호출//////////////////////////////////
        let stu = new ExtentionStudent("green"506070);   
//new라는 키워드를 사용하여 생성자를 만들고 매개변수로 (green, 50, 60, 70)있음 
이걸 stu로 할당
        console.log(stu.sum());       
//콘솔창에 stu.sum()메서드 출력, 상속 받아서 student클래스 기능도 사용 가능
        console.log(stu.total());     
//콘솔창에 stu.total()메서드 출력
        console.log(stu.name)
        
    </script>
</body>
</html>
cs

 

콘솔 출력 확인!!!!!!!!!!!!!!

실습에서는 stu변수 하나만 출력했지만 나중에 많은걸 생성해야할떄는 쓰기 좋을것 같다(객체 리터럴./생성자 와 비슷)

ex)

let stu1 = new ExtentionStudent("green", 50, 60, 70);

let stu2 = new ExtentionStudent("green", 30, 90, 20);

let stu3 = new ExtentionStudent("green", 10, 50, 10);

let stu4 = new ExtentionStudent("green", 80, 60, 10);

 

 


 

class 실습2

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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        console.log("첫번째 클래스")
        //클래스 선언
        class Person {
            constructor(name, age) {  //함수 생성 및 초기화
                this.name = name;  //name변수 기본값 설정 및 변수선언
                this.age = age;    //age변수 기본값 설정 및 변수선언
            }
            speak() { //메소드
                console.log(`${this.name} : hello!!`);  //콘솔에 name : hello!! 출력
            }
            eat() {
                console.log(`${this.age} : 하이!!`)     //콘솔에 age : 안녕!! 출력
            }
        }
        const min = new Person("민영"28);     //클래스 생성자 생성
        console.log(min);                      //min 호출
        console.log(min.name);                 //min.name 호출
        console.log(min.age)                   //min.age 호출
        //메소드 호출
        min.speak();                           //min.speak()메서드 호출
        min.eat();                             //min.eat()메서드 호출
        
 
        //학생클래스 생성
        class Student {           //클래스 선언
            constructor(name, age, enrolled, score) {  //함수 생성 및 초기화
                this.name = name;   //name변수 기본값 설정 및 변수선언
                this.age = age;     //age변수 기본값 설정 및 변수선언
                this.enrolled = enrolled;   //enrolled변수 기본값 설정 및 변수선언
                this.score = score;     //score변수 기본값 설정 및 변수선언
            }
        }
 
        const students = [  //객체가 들어간 배열 
            new Student('A'29true45),     //배열1
            new Student('B'28false80),    //배열2
            new Student('C'30true90),     //배열3
            new Student('D'40false66),    //배열4
            new Student('E'18true66)      //배열5
        ];
        console.log("두번째 클래스")
        console.log(students)     //students 배열 호출
        
 
        //상속과 다형성
        
        class Shape {  // 클래스 선언
            constructor(width, height, color) {   //함수 생성 및 초기화
                this.width = width;     //width변수 기본값 설정 및 변수선언
                this.height = height;   //height변수 기본값 설정 및 변수선언
                this.color = color;     //color변수 기본값 설정 및 변수선언
            }
            draw() { //메소드
                console.log(`${this.color}로 그립니다`); 
//콘솔에 color 로 그립니다 호출
            }
            getArea() { //메소드
                return this.width * this.height;   // width * height 곱해서 돌려줌
            }
        }
 
        //상속 키워드 extends
        class Rectangle extends Shape {  
            //Rectangle 클래스가 Shape 기능을 상속받음 (추가및 수정 가능(오버라이딩))
 
            //메소드 재정의
            //오버라이딩
            //필요한 함수만 재정의한다
            draw() {
                super.draw(); 
//super는 부모요소를 가리킴(부모에서 draw() 메서드 호출)
                console.log("사각형을 그립니다.")  //콘솔에 사각형 그립니다 호출
            }
        }
        class Triangle extends Shape {
            //Triangle 클래스가 Shape 기능을 상속받음 (추가및 수정 가능(오버라이딩))
            draw() {
                super.draw(); //super는 부모요소를 가리킴 (부모에서 draw() 메서드 호출)
                console.log("삼각형을 그립니다"//콘솔에 삼각형 그립니다 호출
            }
 
        }
        const rectangle = new Rectangle(2020'blue');  
//new 키워드를 사용하여 Rectangle 생성자 생성
        console.log("아래쪽 세번째 클래스")
        rectangle.draw();  //rectangle클래스 draw 메서드 호출
        console.log(rectangle.getArea());  //콘솔에 rectangle.getArea()메서드 호출
        console.log(rectangle); //콘솔에 rectangle 호출
        
 
        const triangle = new Triangle(2040"yellow"); 
//new 키워드를 사용하여 Triangle 생성자 생성
        triangle.draw();   //triangle클래스 draw 메서드 호출
        console.log(triangle.getArea()); //콘솔에 rectangle.getArea()메서드 호출
        console.log(triangle);  //콘솔에 triangle 호출
    </script>
</body>
</html>
cs

콘솔에 출력!!!!!!!!!!!!!!!!!

 

 

 

 

 

 

 

728x90
반응형

'javascript > javascript 고급문법' 카테고리의 다른 글

[javascript] this키워드  (0) 2023.01.23
[javascript] Modules  (0) 2023.01.11
[javascript]구조분해할당과 spread,rest  (0) 2023.01.05
[javascript]정규표현식  (0) 2022.12.23
[javascript]BOM(Browser Object Model)  (0) 2022.12.14

댓글