html,css,js 공부

(2024 03 12) js 19일차(클래스)

ari0930 2024. 3. 12. 15:54

(2024 03 12) js 19일차

 

클래스

=>객체를 생성하기 위한 설계도로 클래스 안에는 필드(속성)와 메서드로 구성되어 있다

 

추상화

=>핵심적인  기능 또는 데이터만 간추려 내어 표현하는 과정을 의미한다 

=>객체의 공통적인 특성을 축출하여 추상클래스로 정의 하여 상의 클래스로 만든다.

예를 들어 자동차를 추상해 보면

자동차 종류는 여러가지 있어도 기본적으로 장도차에는 가속,멈춤,회전등 공통적인 기능들이 존재한다

이런 공통적인 기능들을 모아서 하나의 클래스로 만드는것을 추상화라 한다.

 

        //사각형 클래스
        class Rectangle{
            //생성자
            #width
            #height
            constructor (width,height) {
                if (width<=0 && height <=0){
                    throw "길이를 잘못입력하셨다"

                }
                this.#width=width
                this.#height=height
            }
            //둘레구하는 메소드
            getperimeter() {
                return 2*(this.#width+this.#height)
            }
            //넓이 구하는 메소드
            getArea() {
                return this.#width*this.#height
            }

            setwidth(value){
                if (value<=0){
                    throw "길이를 잘못입력하셨다"

                }
                this.#width=value
            }

            getwidth() {
                return this.#width
            }

        }

        //인스턴스
        const rectange=new Rectangle(10,20)
        rectange.width=-10
        console.log(rectange.getperimeter())
        console.log(rectange.getArea())
        console.log('------')
        //세터 게터
        rectange.setwidth(40)
        console.log(rectange.getwidth())
        console.log('------')



        //정사각형 클래스 상속하는법
        class square extends Rectangle{

            constructor(length){
                super(length,length)
            }
            
        }

        const squar=new square(10)
        console.log(squar.getperimeter())
        console.log(squar.getArea())

 

상속

=>하나의 클래스가 다른 클래싀 특성(필드,매개변수등을 ) 사용하는것을 의미한다

사용법

class 클래스이름 extends 부모클래스 이름{

}

 

위의 코드를 보면 square라는  클래스를 만들었지만 그 클래스 내부에 넓이와 둘레 구하는 법을 만들어 두지 않아도 부모클래스로부터 상속 받으면 부모 클래스 내부의 것들을 사용할수 있다.

 

super()=> 부모의 생성자 함수 호출

           =>   constructor (width,height) 이부분을 호출하는것이다 

 

private 이란

=> 필드나 메서드에 #을 붙이면서 선언할수 있는데 이렇게 선언한것들은 외부에서 접근할수 없게된다

같은 클래스 내에서만 접근하여 수정할수 있다.

 

게터(Getter) 세터(Setter)

=> 게터는 클래스 내부값을 읽어오는역할을 하며

=> 세터는 private로 선언된 변수나 함수 내부에서 변경하게 하도록 값을 지정한다

위 Rectangle 함수에서 getwidth 와 setwidth 가 있는데  getwidth는 현재 width값을 출력하고

setwidth는 이미 지정된 width값을 변경한다.

        class square{
            //생성자
            #length
            static #counter = 0 //private 와 static 특성 한번에 적용

            static get counter () {
                return square.#counter

            }
            constructor (length) {

                this.length=length 
                //this.length 는 set length를 찾아감

                square.#counter+=1
            }

            get length() {
                return this.#length
            }
            //둘레구하는 메소드
            get perimeter() {
                return 4*(this.#length)
            }
            //넓이 구하는 메소드
            get Area() {
                return this.#length*this.#length
            }

            set length(length){
                if (length<=0){
                    throw "길이를 잘못입력하셨다"

                }
                this.#length=length
            }

            static areaOf(length){
                return length*length
            }

        }

        const squarea= new square(10)
        console.log(`한변의 길이: ${squarea.length}`)
        console.log(`둘레: ${squarea.perimeter}`)
        console.log(`넓이: ${squarea.Area}`)
        const squareb= new square(15)
        const squarec= new square(20)
        //스테틱 메소드 사용하기
        console.log(`총 몇번 만들었니 ${square.counter}`)
        console.log(`한변의 길이 20인 도형의 넓이: ${square.areaOf(20)}`)

static 로  선언된 메서드나 필드값들은 클래스의 인스턴스(객체) 와 상관없이 사용할수 있다 

 

console.log(`총 몇번 만들었니 ${square.counter}`) 인스턴스 선언 하지 않고도 클래스 내부의 변수값을 읽어올수있다. 

 

        //오버라이드

        class lifecyle {
            call () {
                this.a()
                this.b()
                this.c()
            }

            a(){console.log("a를호출")}
            b(){console.log("b를호출")}
            c(){console.log("c를호출")}
        }

        class child extends lifecyle {
            //오버라이드 한거

            a(){
                console.log("자식의 a를호출")}
        }
        //인스턴트 생성
        new lifecyle().call()
        console.log("-------------")

        new child().call()

결과

a를호출
b를호출
c를호출

-------------
자식의 a를호출
b를호출
c를호출

오버라이드

=> 부모 클래스에서 이미 정의된걸 자식 클래스에서 다시 재정의 하여 사용하는것을 말한다 

 

위 코드에서 child 클래스에는 call이라는 메서드와 b,c메서드가 없다 그러나 child().call()을 하면 

부모의 call 메서드를 실행할수 있는데 이때  자식에도 있고 부모에도 이름이 같은 메서드가 있을때에는 자식의 것으로 출력되어 "자식의 a를 호출"이라고 출력된다. 

반응형

'html,css,js 공부' 카테고리의 다른 글

(2024 03 14) js 21일차  (0) 2024.03.14
(2024 03 11)JS 18일차  (0) 2024.03.11
(2024 03 07-08)16-17일차 js  (1) 2024.03.08
(2024 03 07) js 15일차  (0) 2024.03.07
(2024 03 05) js 14일차  (0) 2024.03.05