JavaScript ES6 문법 - Extends / Super / Getter / Setter

Apeachicetea·2021년 11월 4일
0

JavaScript ES6

목록 보기
4/6

Extends

유사한 class를 쉽게 더 만들고 싶을때 쓰인다.

Extends & Super

extends해서 만든 class는 this를 바로 사용하지 못한다.
super() 다음에 사용해야 한다.


    class 할아버지 {
      constructor(name, name2) {
        this.= 'kim';
        this.이름 = name;
        this.별명 = name2;
      }
      
      sayHi() {
        console.log('안녕! 나는 할아버지에요.');
      }
      
    }

Super()의미

위치에 따라 다르다.
1. 물려받은 class의 constructor라는 뜻이다.(prototype도 상속된다.)
2. 부모class의 prototype을 의미한다.


    class 아버지 extends 할아버지 {
      constructor(name, name2) {
        super(name, name2);
        //super()의 뜻 : 물려받은 class의 constructor라는 뜻이다.(prototype도 상속된다.)
        this.나이 = 50;
      }

      sayHi() {
        console.log('안녕! 나는 아버지에요.');
        super.sayHi();
        //super 또 다른 의미 : 부모class의 prototype을 의미한다.
      }

    }

let 아버지1 = new 아버지('만덕', '만득');

콘솔


Getter / Setter

함수를 만들어 object 데이터를 다루는 이유

  1. object 자료가 복잡할 때 이득
  2. object 자료 수정시 편리

복잡한 소괄호 쓰기 싫다면 set/get을 사용!

set 데이터 변경하는 함수에
get 데이터 꺼내쓰는 함수에

set함수들(setter) 파라미터가 1개가 있어야 한다.
get함수들(getter) return이 있어야 한다.

예시


    class 인간 {
      constructor() {
        this.name = 'Park';
        this.age = 20;
      }

      get nextAge() {
        return this.age + 1;
      }

      set setAge(a) {
        this.age = a; 
      }

    }

    let 인간1 = new 인간();

콘솔

기존 문법에 의하면
인간1.nextAge();
인간1.setAge(20);으로 작성해야 하지만
set/get을 이용하면 소괄호를 생략할 수 있다.

profile
웹 프론트엔드 개발자

2개의 댓글

comment-user-thumbnail
2024년 7월 24일

Hey guys! For those who love sports and live betting, https://melbet-brasil.net/melbet-ao-vivo-participe-de-apostas-com-transmissoes-online/ is top of the line. I recently took part in MelBet's live betting and the experience was electrifying. The possibility of betting while watching the matches in real time is an unparalleled experience. MelBet offers a wide coverage of sporting events with competitive odds, which really maximizes the chances of winning. What's more, the interaction with other punters and the high-quality broadcast make it all the more engaging. I highly recommend it to anyone in Brazil looking for a complete live betting experience.

답글 달기
comment-user-thumbnail
2024년 8월 10일

Hi, I'm also a programmer and in between work I'm a casino gambler. I have played at several online casinos, but https://staycasino1.bet/ really stands out among them. The variety of games is impressive and the interface was easy to navigate. What I like most is how quickly I was able to start earning real money. Bonuses are generous and payouts are fast. Whether you're an experienced player or new to online casinos, Staycasino is worth a try!

답글 달기