본문 바로가기
개발/JavaScript

2023.04.10 JavaScript의 클래스심화, 상속의활용

by 상달군 2023. 4. 10.
728x90

목차

1. JavaScript의 클래스심화

  • Static(정적프로퍼티)
  • 문제. 카운터 만들기

2. JavaScript의 상속의 활용

  • 상속 기본
  • 문제. 정직원, 아르바이트생 한달 급여 계산하기

3. JavaScript의 Wrapper

  • Primitive Types
    • 환경을 찍어주는 명령어!
  • 동등 연산자
  • URL,URI대한 추가 설명

1. JavaScript의 클래스심화

 

1-1.Static(정적프로퍼티)

  • 정적 프로퍼티 및 메소드를 생성 할 수 있다. 
  • 미리 메모리에 올릴수 있는 애들 
  • 클래스 레벨 메소드(static을 사용한)에서는 this를 참조 할 수 없다.

예시 1)

        // static
        class Fruit {
            static count_fruit = 10; //정적프로퍼티: 객체를 생성한적 없는 메모리에 올려 놓는다. this를 쓰지 않는다!
            constructor (name, emoji){
                this.name = name;
                this.emoji = emoji;
            }
            display = () => {
                console.log(`${this.name}: ${this.emoji}`);
            }

            // 바나나 메소드 생성
            // 위에 애들이랑 따로 놀기때문에 this를 사용할수 없다.
            static makeBanana(){
                return new Fruit('banana', '🍌');
            }
        }

        const apple = new Fruit('apple', '🍎');
        const orange = new Fruit('orange', '🍊');
        console.log(apple);
        console.log(apple.name);
        console.log(orange);
        console.log(orange.name);

        console.log(Fruit.count_fruit);// 객체를 만든적이 없지만 사용할수 있다. 스테틱이기 때문에.

        const banana = Fruit.makeBanana();
        console.log(banana);
        console.log('-----------');

예시 2) #을 이용하여 프라이빗한 상수 사용하기

        // #을 이용하여 프라이빗 한 상수를 잡아줄수 있다.
        class Dog{
            #name;// #을 이용해서 프라이빗 하게 막아준다!!
            #color;
            constructor(name, color){
                this.#name = name;
                this.#color = color;
            }

            // 프라이빗 한 변수의 값을 교체 하는 메소드 
            // 프러퍼티명과 꼭 일지할 필요는 없음 !
            set name(value){
                console.log('set', value);
                this.#name = value;
            }
            //프라이빗 한 값을 불러 올때 get으로 만들어줘야한다.
            get name(){
                return `이름:${this.#name}`;
            }

            run = () => {
                console.log(`${this.#color} 색상의 강아지 ${this.#name}이 달립니다.`);
            }

            // 프라이빗 한 메소드
            #eat = () => {
                console.log(`${this.#name}는 먹습니다.`);
            }

            // 프라이빗 하기 때문에 #eat를 불러 사용한다. 
            //같은 클래스 안에 존재 하기 때문에 사용가능하다. 
            myEat = () => {
                this.#eat();
            }

        }
        const Rucy = new Dog('루시', '흰색');
        console.log(Rucy);
        // Rucy.name = '류씨'; // 프라이빗한 name값이 아닌 새로운 name의 값이 생겨난다. 
        // Rucy.#name = '류씨'; // 프라이빗한 name값에 접근 했기때문에 신텍스에러가 발생한다.  
        console.log(Rucy);

        // 위에서 set name메소드를 생성해줬기 때문에 값을 변경이 가능하다. 
        Rucy.name = '류씨';
        console.log(Rucy);

        console.log(Rucy.name);// 값을 찍어주고 싶은데 에러가 발생함 ㅠㅠ
        // 해결을 위해 class안에 get을 만들어 주어야한다!

        Rucy.run();
        // Rucy.eat(); // 그냥 접근 안됨
        Rucy.myEat(); // 새로운 메소드를 만들어서 접근 !
        console.log('--------------');

1-2.문제. 카운터 만들기

        //문제. 
        // 카운터 만들기
        // 카운터를 0으로 값을 초기화 한 뒤 하나씩 숫자를 증가할수 있는 메소드로 구현
        class Counter{
            #value;
            constructor(value){
                if(isNaN(value) || value < 0) {// isNaN()함수: 숫자가 아닐경우 NaN이 나오는
                    this.#value = 0;  
                }else {
                    this.#value = value;
                }
            }

            get value(){
                return this.#value;
            }
            increment = () => {
                this.#value++;
            }
        }
        const cnt = new Counter(0);
        console.log(cnt.value); //  처음 셋팅값 
        cnt.increment(); // 1 // 값에는 접근 할수 없도록 만들기
        cnt.increment(); // 2
        console.log(cnt.value); // increment() 두번돌아서 출력값은 2
        console.log('-------------------');

 


2. JavaScript의 상속의 활용

2-1.상속 기본

- 상속이란 부모 클래스의 내용을 자식 부모에게 내용을 전달해줄수 있는것 

- 사용법 

          class 클래스명 extends (부모)클래스명

        class Animal {
            constructor(color){
                this.color = color;
            }
            eat(){
                console.log('먹는다!');
            }
            sleep(){
                console.log('잔다!');
            }
        }

        class Dog extends Animal{ // class 클래스명 extends 부모클래스명
            play(){
                console.log('논다!');
            }
        }

        const Rucy = new Dog('white');
        console.log(Rucy);
        Rucy.eat();
        Rucy.sleep();
        Rucy.play();


        class Cat extends Animal{
            constructor(color, name){ // Cat클래스용으로 오버라이딩 하기 
                super(color); //부모는 파라미터 color이 필요하기 때문에 color를 보내줘야한다. 
                this.name = name; // name은 부모께 아니고 자식꺼임으로 그냥 프로퍼티해준다. 
            }
            // 메소드 오버라이딩
            eat(){
                console.log('맛있게 먹는다!');
            }
        }
        const Horang = new Cat('black', '호랑이');
        console.log(Horang);
        Horang.eat();
        console.log('------------');

2-2.문제. 정직원, 아르바이트생 한달 급여 계산하기

        // 문제.
        // 정직원과 아르바이트생을 나타낼 수 있는 클래스를 생성
        // 클래스명 FullTimeEmployee(정직원), PartTimeEmployee(알바)
        // 직원의 정보: 이름 부서명 한달근무시간 [프로퍼티]
        // 급여: 정직원(20,000원), 아르바이트(10,000원)
        // 매달 직원들의 정보를 이용해서 한달 급여를 계산하는 메소드를 구현(calculatePay())
        // 예) kim.calculatePay() -> 한달 급여
        
         class Employee1{
            constructor(name, department, hoursPerMonth, payRate){
                this.name = name;
                this.department = department;
                this.hoursPerMonth = hoursPerMonth;
                this.payRate = payRate;
            }
            calculatePay1(){
                return this.hoursPerMonth * this.payRate;
            }
        }

        class FullTimeEmployee1 extends Employee1{
            static PAY_RATE = 20000;
            constructor(name, department, hoursPerMonth){
                super(name, department,hoursPerMonth, FullTimeEmployee1.PAY_RATE);
            }
        }
        class PartTimeEmployee1 extends Employee1{
            static PAY_RATE = 10000;
            constructor(name, department, hoursPerMonth){
                super(name, department,hoursPerMonth, PartTimeEmployee1.PAY_RATE);
            }
        }

        const kim1 = new FullTimeEmployee1('김사과', '개발자', 160);
        const oh1 = new PartTimeEmployee1('오렌지', '디자이너', 100);

        console.log(kim1.calculatePay1());
        console.log(oh1.calculatePay1());


3. JavaScript의 Wrapper

 

3-1.Primitive Types

  • 7가지 Primitive Types: string, number, bigint, boolean, undefined, symbol, null
  • 기본 타입은 객체가 아니다.
  • 고정되어 있는 타입이라고 보면 된다.( 불변 타입이라고도 합니다. )
  • 기본 타입은 프러퍼티와 메서드를 정의할 수 없다.
  • new 키워드를 사용하여 기본 타입을 래퍼(wrapper) 객체로 생성할 수 있지만, 주로 사용하는 방법은 아니다.

 

    let a = 'apple';  == let b = new String('apple'); // true: 값은 같지만 타입이 다르다. 
    let a = 'apple';  === let b = new String('apple'); // false: 값은 같지만 타입이 다르다. 



                                                      ✔객체화!
                                                         - string -> String
                                                         - number -> Number
                                                         - bigint -> BigInt
                                                         - boolean -> Boolean
                                                         - symbol -> Symbol

 

        const num = 10; // number의 원시 타입 
        console.log(typeof(num)); //소문자 number 원시타입
        console.log(num.toString()); // toString String객체로 변환해주는 함수
        console.log(typeof(num.toString())); // 변경된 String객체 타입 확인하기
        console.log(typeof(num)); //다시 원시타입으로 돌아옴 
        console.log('--------------');

        //지수 표기법 (10의 n승으로 표기하는 방법)
        const x1 = 102;
        console.log(x1.toExponential());
        console.log('--------------');

        // 반올림하여 문자열로 변환
        const x2 = 123.12;
        console.log(x2.toFixed());
        console.log('--------------');

        //로컬형식의 문자형으로 변환
        console.log(x2.toLocaleString('ar-EG')); //('ar-EG') 아랍어로 바꾼것 // 안에 언어 선택가능

        const x3 = 0.1 + 0.2 - 0.2;
        console.log(x3);

✔중요한 예시)

- 어떠한 환경에서 명령어를 보고 있는지를 확인 시켜주는 명령어 

- 우리는 크롬 환경에서 PC를 보고 있기때문에 window객체가 찍히기 됩니다. 

        //환경을 찍어보고 싶을때 
        console.log(globalThis);// Window객체가 찍힌다.

3-2.동등 연산자

 - 기본 타입으로 생성된 변수와 new 키워드를 사용하여 명시적으로 생성된 래퍼객체는 서로 다른 타입이다!! 

    'JavaScript' === 'JavaScript'; // true
    'JavaScript' === new String('JavaScript'); // false
    
    let num1 = 10;
    let num2 = new Number(10);
    num1 === num2; //false

3-3.URL,URI대한 추가 설명

URL, URI(Uniform Resource Identifier)
아스키 문자로만 구성되야 함 (전세계 컴퓨터가 유니코드값이 다를수도 있기 때문에)
- 한글이나 특수문자는 이스케이프 처리 되어야 한다. 

 

※한글 도메인을 구할 수 없어 예를 들어서 진행하였습니다.

    const URL = 'https://코리아아이티아카데미.com';
    const encoded = encodeURI(URL// 이스케이프 처리 해주어야 한다 !
    const decoded = decodeURI(encoded) // 디코드 처리(원래대로 돌려주기)

 

        const URL = 'https://코리아아이티아카데미.com';
        const encoded = encodeURI(URL);
        console.log(encoded);
        const decoded = decodeURI(encoded);
        console.log(decoded);

        // 모든 글자를 인코딩
        const encodedCom = 'https://코리아아이티아카데미.com';
        console.log(encodeURIComponent(encodedCom));

728x90

댓글