Tagged templates
func
string`` μ²λΌ ν
νλ¦Ώ 리ν°λ΄(template literals) μμ νκ·Έ(ν¨μ)λ₯Ό μ¬μ©νλ©΄ν
νλ¦Ώ 리ν°λ΄μ νμ±ν μ μλ€.
μ΄λ κ² μ¬μ©λλ νκ·Έ ν¨μ(Tag function)μλ 첫 λ²μ§Έ μΈμλ‘ λ¬Έμμ΄ κ°μ λ°°μ΄μ΄ μ λ¬λκ³ , λλ¨Έμ§ μΈμλ‘λ ννμμ΄ μ λ¬λλ€.
const person = 'Mike';const age = 28;
function myTag(strings, personExp, ageExp) { console.log(strings); // ["that ", " is a ", "", raw: Array(3)] const str0 = strings[0]; const str1 = strings[1];
const ageStr = ageExp > 99 ? 'centenarian' : 'youngster';
return str0 + personExp + str1 + ageStr;}
const output = myTag`that ${person} is a ${age}`;
console.log(output);// that Mike is a youngster
ννμμ΄ μ¬λ¬ κ°μΌ κ²½μ°μ νκ·Έ ν¨μμμ λλ¨Έμ§ λ§€κ°λ³μ(Rest parameters)λ₯Ό μ¬μ©νλ©΄ λ°°μ΄λ‘ ννμμ λ°μ μ¬μ©ν μ μλ€.
function myTag(strings, ...expressions) { console.log(strings); // ["that ", " is a ", "", raw: Array(3)] console.log(expressions); // ["Mike", 28]}
const person = 'Mike';const age = 28;
const output = myTag`that ${person} is a ${age}`;