■ Tagged literals
Tagged literals은 ``백틱을 사용하여 함수로 문자를 해체할 수 있는 기능입니다.
문자 중간의 단어 순서를 바꾸거나 변수를 제거할 때 사용할 수 있는 문법입니다.
var 이름 = 'kim';
var 지역 = '서울';
function 문자해체(문자들, 변수1, 변수2){
console.log(문자들);
console.log(변수1);
console.log(변수2)
}
만들어진 함수에 tagged literals 문법을 사용해보면,
문자해체`안녕하세요 ${이름} 이고 ${지역}에 살고있습니다.`;
// ['안녕하세요 ', ' 입니다', raw: Array(2)]
// 'kim'
// '서울'
문자와 변수를 분리해서 보여주는 모습을 보여줍니다.
즉, 함수의 첫 번째 파라미터에는 변수 양 옆의 문자가 들어가고 배열을 만들며,
두 번째 이하의 파라미터에는 변수가 들어갑니다.
■ apply, call 함수
apply 함수는 새로운 this 값을 명시하여 함수를 실행할 수 있습니다.
apply 함수는 첫 번째 인자로 this로 사용할 객체를 전달받고, 두 번째 인자로는 적용할 매개변수를 전달받습니다.
function 함수(a, b) {
console.log("첫번째:", a, "두번째:", b);
console.log("합:", this.value);
}
let obj = {value : 5};
함수.apply(obj, [2, 3]);
// 첫번째: 2 두번째: 3
// 합: 5
위의 예제에서는 첫 번째 this자리에 obj 객체를 사용하였고, 두 번째 인자는 각각 2 와 3의 값을 전달하였습니다.
apply 함수는 매개 변수 자리에서 배열을 사용하고,
call 함수는 매개 변수 자리에 배열을 사용하지 않고 순서대로 인자를 받는다는 차이가 있습니다.
function myFunction(a, b) {
console.log("this.value:", this.value);
console.log("a:", a, "b:", b);
}
const obj = {value: 5};
myFunction.call(obj, 2, 3); //this.value: 5 a: 2 b: 3
'JavaScript' 카테고리의 다른 글
JavaScript(default parameter, arguments와 rest parameter) (0) | 2023.06.01 |
---|---|
JavaScript(Spread Operator) (0) | 2023.06.01 |
JavaScript(Hoisting, 전역변수) (0) | 2023.05.30 |
JavaScript(화살표 함수) (0) | 2023.05.29 |
JavaScript(this 키워드) (0) | 2023.05.29 |