일단 시작하기에 앞서
/tsconfig.json
"experimentalDecorators": true
로 변경해준다.
class에 데코레이터 사용하기
클래스 선언 부분 위에 넣어주는 데코레이터.
이 데코레이터는 기존 클래스의 정의를 확장해주는 역할을 한다.
function modalElement(el: string, elementId: string) {
return function (constructor: any) {
const name = new constructor();
const element = document.getElementById(elementId);
if (element) {
element.innerHTML = el;
element.querySelector("h1")!.textContent = name.name;
}
};
}
@modalElement("<h1>new modal</h2>", "app")
class Person222 {
일반적인 데코레이터는 아래와 같지만
function Logger(constructor: Function) {
console.log("logging");
console.log(constructor);
}
@Logger
팩토리화를 시켜보자
function Logger(logstr: string) {
return function (constructor: Function) {
console.log(logstr);
console.log(constructor);
};
}
@Logger("logging-person")
이전과 달리 데코레이터함수 사용시에 인자로 특정 값을 전달 할 수 있도록 해준다.
위와 같이 이전의 데코레이터 로직을 리턴해주는 콜백함수로 넣어준다.
좀더 연습삼아 작성해본다면
function modalElement(el: string, elementId: string) {
return function (constructor: any) {
const name = new constructor();
const element = document.getElementById(elementId);
if (element) {
element.innerHTML = el;
element.querySelector("h1")!.textContent = name.name;
}
};
}
@modalElement("<h1>new modal</h2>", "app")
class Person222 {
name = "max";
constructor() {
console.log("aaa");
}
}
const per11 = new Person222();
return function (constructor: any) {
const name = new constructor();
이 부분에서 인자로는 person22 클라스 자체가 constructor인자로 전달되며
name.name 으로 클라ㅡ 내부 프로퍼티에 접근이 가능하다.
실행순서
데코레이터의 실행순서는
자바스크립트의 규칙대로 팩토리 외부의 함수가 순서대로 실행되고 팩토리 내부의 함수는
데코레이터를 선언한 아래에서 위 순서대로 실행된다.
function Logger(logstr: string) {
console.log("1번");
return function (constructor: Function) {
console.log("4번");
console.log(logstr);
console.log(constructor);
};
}
function modalElement(el: string, elementId: string) {
console.log("2번");
return function (constructor: any) {
console.log("3번");
const name = new constructor();
const element = document.getElementById(elementId);
if (element) {
element.innerHTML = el;
element.querySelector("h1")!.textContent = name.name;
}
};
}
@Logger("logging-person")
@modalElement("<h1>new modal</h2>", "app")
class Person222 {
name = "max";
constructor() {
console.log("aaa");
}
}