개발에 AtoZ까지

[ES6][JS] 함수 호출 및 Tagged Templates 본문

프론트엔드/JAVASCRIPT

[ES6][JS] 함수 호출 및 Tagged Templates

AtoZ 개발자 2022. 11. 13. 21:50
반응형

목차

- 함수 호출
- Tagged Templtes식 호출


 

함수 호출

일반적인 함수호출

const multiple = (a,b) => {
    return a*b;
} 

console.log(multiple());

Tagged Templates식 호출

태그를 사용하여 템플릿 리터럴(Template Literal)을 함수로 파싱할 수 있습니다.

✏️ 템플릿 리터럴(Template Literal)이란?

더보기

내장된 표현식을 허용하는 문자열 리터럴로 표현식 / 문자열 삽입, 여러 줄 문자열, 문자열 형식화, 문자열 태깅등 다양한 기능을 제공합니다.

이렇게 템플릿 리터럴을 사용해서 표현하면 런타임 시점에서 일반 JS 문자열로 처리 및 변화되어 동작합니다.

const num1 = 2;
const num2 = 3;

const multiple = (a, b) => {

  return a*b;
}
multiple`${num1} ${num2}`;
//6 출력됨

📌 언제 Tagged Templates을 사용할까?

컴포넌트의 스타일링 할때 사용할 수 있는 Styled-component에서 많이 사용됩니다

import styled from 'styled-component';

const Container = styled.div`
    width: 100%;
    size: 30px;
`

위의 코드에서 div는 함수로 볼 수 있습니다

styled-component에서 실제 정의한 내용을 보더라도 div의 타입은 function 입니다. 실제 구현체를 보면 입력받은 태그연사자로 정의된 함수를 호출하고 속성값들을 param으로 받아 실행됩니다

export interface ThemedStyledFunctionBase<
    C extends keyof JSX.IntrinsicElements | React.ComponentType<any>,
    T extends object,
    O extends object = {},
    A extends keyof any = never
> {
    (first: TemplateStringsArray): StyledComponent<C, T, O, A>;
    (
        first:
            | TemplateStringsArray
            | CSSObject
            | InterpolationFunction<ThemedStyledProps<StyledComponentPropsWithRef<C> & O, T>>,
        ...rest: Array<Interpolation<ThemedStyledProps<StyledComponentPropsWithRef<C> & O, T>>>
    ): StyledComponent<C, T, O, A>;
    <U extends object>(
        first:
            | TemplateStringsArray
            | CSSObject
            | InterpolationFunction<ThemedStyledProps<StyledComponentPropsWithRef<C> & O & U, T>>,
        ...rest: Array<Interpolation<ThemedStyledProps<StyledComponentPropsWithRef<C> & O & U, T>>>
    ): StyledComponent<C, T, O & U, A>;
}
반응형
Comments