TIL

[TIL] 2021년 12월 23일

건브로 2021. 12. 23. 22:19

1. 오늘 배운 것

 

나머지 매개변수

변수에 대한 class의 this

 

2. 나머지 매개변수

이 개념은 ES6부터 사용 가능해졌다.

 

spread 연산자를 사용하기 때문에

최소 ES6부터 사용 가능할 거라고 추측은 가능하다.

 

이 개념의 핵심은 해당 함수의 인수들이 선언된 함수의 매개변수(파라미터)가

바로 배열로 만들어져서 이 매개변수를 배열로써 바로 사용 가능하다. 

 

//타입스크립트
function add(...numbers: number[]){
	console.log(numbers);
    const data = numbers.reduce((currentResult, currentValue) => {
    	console.log("currentResult" + currentResult);
        console.log("currentValue" + currentValue);
        return currentResult + currentValue;
    }, 0);
    console.log(data);
}
add(1, 2, 3);
//결과
[1, 2 ,3];
currentResult 0
currentValue 1
currentResult 1
currentValue 3
currentResult 4
currentValue 5
9

 

 

3. 변수에 대한 class의 this

나는 class에 좀 약한 편이다.

 

아니다.

 

객체지향프로그래밍(OOP)에 약한 걸지도 모르겠다.

 

또 이렇게 내가 약하다고 느낀 이유는

React를 쓰면서 클래스형 컴포넌트보다 함수형 컴포넌트를 즐겨 썼기 때문이다.

 

this는 클래스 내의 변수를 가리킨다.

그래서 전역변수와 클래스 내 변수 이름이 같아도 this.변수가 있다면 괜찮다. 

 

//타입스크립트

class Animal{
	kind: string;
	constructor(kind: string){
    	this.kind = kind;
    }
    beBorn(){
    	console.log(this.kind);
    }
}
const cat = new Animal("Mammalia");
cat.beBorn();
//결과
//Mammalia;

 

//타입스크립트

class Animal{
	kind: string;
	constructor(kind: string){
    	this.kind = kind;
    }
    beBorn(){
    	console.log(this.kind);
    }
}
//1. 바로 변수에 객체의 함수를 적용할 때

const cat = new Animal("Mammalia");
const beBornAsCat = cat.beBorn();
//결과
//kind가 undefined이면서 이것에 대해 type error가 나온다

//2. 바로 변수의 속성으로써 적용했을 때
const cat2 = { beBorn: cat.beBorn };
cat2.beBorn();
//결과
//undefined

 

이 코드와 같이 하면 오류가 나거나 undefined로 나온다.

이유는 animal class의 메서드는 클래스 내의 변수를 가리키기 때문이다.

하지만, beBornAsCat은 클래스를 가지고 온게 아닌 함수 자체를 가지고 왔기에 읽지 못한다.

 

그러니 아래의 코드처럼 바꿔야한다.

 

//타입스크립트

class Animal{
	kind: string;
	constructor(kind: string){
    	this.kind = kind;
    }
    beBorn(this: Animal){
    	console.log(this.kind);
    }
}
const cat = new Animal('Mammalia');
const cat2 = { kind: 'Mammalia', beBorn: cat.beBorn };
cat.beBorn();
//결과
//Mammalia

 

여기서 주의할 것은 cat2의 속성들은 Animal class와 일치해야 하므로

마음대로 속성 이름을 작명해서는 안된다.

 

그리고 beBorn은 그냥 함수가 아니기에 beBorn의 매개변수를 this: Animal로 해야 한다.

 

 

4. 느낀 점

 

es6 문법을 대부분 안다고 생각했는데, 내가 안 써봤던 문법이 있었다.

그 문법을 왜 이제 알았을까...

 

자바스크립트는 점점 더 사용자 편의성을 강조하는 언어가 돼가고 있다.

 

하지만, 편의성에 길들여져서 그 편의가 실력이라고 생각하면 안 된다고 생각한다.

편의만 생각하다 보니 지금 내가 class를 잘하지 못 한다..

 

이번 기회에 계속 TIL 작성하면서 부족한 점을 찾고,

class를 세부적으로 다뤄봐야겠다. 프로토타입도...

'TIL' 카테고리의 다른 글

[TIL] 2021년 12월 28일  (0) 2021.12.28
[TIL] 2021년 12월 27일  (0) 2021.12.27
[TIL] 2021년 12월 21일  (0) 2021.12.21
[TIL] 2021년 12월 20일  (0) 2021.12.20
[TIL] 2021년 12월 19일  (0) 2021.12.19