일반적인 객체 생성
type Box = {
width: number;
height: number;
borderRadius: number;
backgroundColor: string;
borderWidth?: number;
['className']?: string;
}
const box: Box = {
width: 200,
height: 200,
borderRadius: 5,
backgroundColor: 'red',
borderWidth: 10,
['className']: 'box rounded', // == className: 'box rounded'
}
단점: box 내 property 의 이름 변경 시 수많은 변수에 객체가 할당되어 있다면
할당된 모든 객체의 property 이름을 변경해 주어야 한다.
함수를 이용한 객체 생성
function makeBox(
width: number,
height: number,
borderRadius: number,
backgroundColor: string,
borderWidth?: number,
className?: string,
) {
return {
width, // width: width,
height, // height: height,
borderRadius, // borderRadius: borderRadius,
backgroundColor, // backgroundColor: backgroundColor,
borderWidth, // borderWidth: borderWidth,
className, // className: className,
}
}
const boxFunc = makeBox(100, 100, 0, 'blue');
// 위의 단점을 보완할 수 있다.
클래스를 이용한 객체 생성
class Shape {
constructor(
public width: number,
public height: number,
public borderRadius: number,
public backgroundColor: string,
public borderWidth?: number,
public className?: string
) {
this.width = width;
this.height = height;
this.borderRadius = borderRadius;
this.backgroundColor = backgroundColor;
this.borderWidth = borderWidth;
this.className = className;
}
}
const boxShape = new Shape(100, 100, 0, 'blue');
객체 변형
// 객체 복사 안됨
const box1 = box;
// 객체 복사 됨
// (1)
const box2 = Object.assign({}, box);
// assign(a, A, B, C ...) 함수는 새로운 객체 a 에 A 객체의 데이터를 넣고
// B 객체부터 객체의 데이터를 a 객체에 오버라이딩 한다.
// (2)
const box3 = { ...box, borderRadius: 10 };
// 많이 사용됨
// (3)
const box4 = JSON.parse(JSON.stringify(box));
// box 객체의 데이터를 JSON 형식의 문자열로 변형한 다음,
// JSON 형식의 객체로 변형하여 box4에 할당한다.
// (4)
const {
currentTarget: {value, tagName, width, id}
} = event;
// 이벤트 Callback 함수의 매개변수인 event로,
// event 안에 존재하는 property만 가져오는 방법이다.
// 위의 선언 방식은 아래와 같다.
// const value = event.currentTarget.value;
// const tagName = event.currentTarget.tagName;
// const width = event.currentTarget.width;
// const id = event.currentTarget.id;
// ※ const 의 변수이름을 key의 이름과 같게 하도록 하는 것 같지만
// key가 아닌 value의 이름이 const의 변수이름으로 오게 된다.
// const {
// currentTarget: {value: value, tagName: tagName, width: width, id: id}
// } = event;
Circle 클래스 객체 → 원에 대한 객체
Rect 클래스 객체 → 사각형에 대한 객체
→ 각 객체에 데이터로 그치는 것이 아니라 객체 자체에 데이터, 동작, 고유값 등 프로그래밍의 도구로 활용할 수 있는 객체의 성격을 가지게 된다.