# class, extends, getter, setter 연습문제

Doozuu·2022년 11월 30일
0

Javascript

목록 보기
30/99

1. 직접 class 구조 만들어보기

class 강아지{
	constructor(,색깔){
    	this.type =; // 주의: , 가 아니라 ; 써줘야함.
        this.color = 색깔;
    }
}

var 강아지1 = new 강아지('말티즈','white');
var 강아지2 = new 강아지('진돗개', 'brown');

정답!



2. Extends

class 강아지{
	constructor(,색깔){
    	this.type =;
        this.color = 색깔;
    }
}

class 고양이 extends 강아지{
	constructor(,색깔,나이){
     super(,색깔);
     this.age = 나이;
    }
}
var 고양이1 = new 고양이('코숏','white',5);
var 고양이1 = new 고양이('러시안블루','brown',2);

정답!



3. instanceof ⭐️

class 강아지{
	constructor(,색깔){
    	this.type =;
        this.color = 색깔;
    }
    한살먹기(){
    	if(this instanceof 고양이){
        	this.age++;
        }
    }
}

class 고양이 extends 강아지(){
	constructor(,색깔,나이){
    super(,색깔);
   	 this.age = 나이;
    }
}

a instanceof b

: a가 b로부터 생성된 오브젝트인지 아닌지를 T/F로 알려주는 연산자.



4.get/set ⭐️

class Unit{
	constructor(){
    	this.공격력 = 5;
        this.체력 = 100;
    }
	get battlePoint(){
        return this.공격력 + this.체력;
    }
    set heal(힐링){
        this.체력 = this.체력 + 힐링;
    }
}

var 쎈애 = new Unit();

console.log(쎈애.battlePoint);
쎈애.heal = 50;

getter에는 parameter 쓰면 안됨!, return 써줘야함



5.get/set ⭐️

var data = {
  odd : [],
  even : [],
  set 분류(...param){
  	param.forEach(num)=>{
    	if(num % 2 == 1){
        	this.odd.push(num)
        }else{
        	this.even.push(num)
        }
    })
  },
  get 정렬(){
  	return [...this.odd, ...this.even].sort()
  }
}

data.set = 1,2,3;
data.정렬;
  1. 몇 개가 들어올지 모르기 때문에 rest parameter(...)이용해서 array에 저장.
  2. forEach 사용해서 하나씩 짝수/홀수 분류(array이기 때문에 forEach 사용가능)
  3. this 값을 잘 가리키기 위해 arrow function 사용
  4. array에 값을 넣기 위해 push() 사용.
  5. 두 개의 array를 합치기 위해 spread operator(...) 사용.
  6. 순서대로 정렬하기 위해 sort() 사용.
profile
모든게 새롭고 재밌는 프론트엔드 새싹

0개의 댓글