JavaScript 有趣的冷知識(shí): 標(biāo)簽?zāi)0?tagged template)
不曉得大家在利用 React.js 開發(fā)網(wǎng)頁(yè)的時(shí)候有沒有用過一個(gè)很好用的組件叫 styled-components,styled-components 是一個(gè)用來產(chǎn)生元素樣式的組件,讓你可以在 JSX 中編寫 css 達(dá)到** CSS-IN-JS** 的技巧,講了這么多就是因?yàn)?styled-component 的官方文件有說了這句話:
This unusual backtick syntax is a new JavaScript feature called a tagged template literal.
這個(gè) tagged template literal 讓我有點(diǎn)好奇了,因?yàn)橹霸谑褂?styled-components 的時(shí)候有發(fā)現(xiàn)明明要產(chǎn)生元素的 method 都是 function,可是在 styled-compoents 中卻看不到任何 "平常" 會(huì)使用的 call function 技巧,后來仔細(xì)去看了 MDN 才知道原來這個(gè)是 ES6 新進(jìn)的方法,而我直到現(xiàn)在才知道,只能說自己認(rèn)識(shí)的 ES6 真的太少了。
Template Strings
在開始講 tagged template literal 時(shí),必須要先講一下 template strings,相信有在使用 ES6 的人都知道 template strings 是非常好用的方法,解決了以往組合字串上需要用冗長(zhǎng)的加號(hào)不斷的拼接。
// ES5
var myName = '前端小智'
console.log("Hello " + myName + '!')
// 'Hello 前端小智!'
// ES6
const myName = '前端小智'
console.log(`Hello ${myName}`)
// 'Hello 前端小智!'
甚至 template strings 也可以利用 multi-line 的效果進(jìn)而達(dá)到換行的效果。
// ES5
console.log('Hello\n' + '前端小智')
// Hello
// 前端小智
// Es6
console.log(`
Hello
前端小智
`)
// Hello
// 前端小智
看到上面的multi-line 寫法有沒有瞬間覺得跟在寫styled-components 很像呢
其實(shí) template strings 的寫法跟接下來要講的 tagged template literal 可以說是息息相關(guān),這也是為甚麼要前必須要先提到 tagged template literal 的原因。
Tagged Template Literal
tagged template literal 簡(jiǎn)單來說就是讓你可以用另一種方式進(jìn)行 function call,通常我們認(rèn)知的 function call 都是利用小括號(hào)的方式進(jìn)行,并且在小括號(hào)中傳入要讓此 function 使用的參數(shù),但 tagged template literal 可以讓你利用 template 的技巧進(jìn)行 function call,寫法就跟上面介紹的 template strings 可以說是一模一樣。
在上面的例子可以看到輸出的格式有點(diǎn)奇怪,竟然是個(gè)數(shù)組而不是單純的字符串而已,這是因?yàn)?JavaScript 要把 template string 記錄起來,這樣才能把 template string 中的變量抓出來,畢竟 function call 最重要的就是要把參數(shù)傳進(jìn)去。
知道了該特點(diǎn)后,接下來我們嘗試用這種方式傳參數(shù)進(jìn)去 function 內(nèi),就像下面這樣。
沒想到還是沒辦法把完整的字串顯示出來,其實(shí)利用 tagged template literal 的方式進(jìn)行 function call 時(shí),第一個(gè)參數(shù)是 template strings 中的 raw strings 也就是除了變量以外的其他字串的集合,會(huì)是一個(gè)數(shù)組,其余的參數(shù)則是會(huì)根據(jù) template strings 中帶入的變量一一的列舉出來。
舉例來說:假如在 template strings 中一共傳入了兩個(gè)變數(shù),則這兩個(gè)變量都會(huì)被當(dāng)作此 function 中的第二及第三個(gè)參數(shù)帶入,事例如下。
但這樣寫真的是很丑,而且你很難預(yù)期這個(gè)在這個(gè) template strings 中一共會(huì)傳多少個(gè)變量進(jìn)去,這時(shí)候如果要讓這個(gè) function 寫起來比較好看可以用 ES6 的 rest parameter 的方式,只是會(huì)把變量都變成數(shù)組,所以要使用變量時(shí)要記得解構(gòu)出來,事例如下:
總結(jié)這次介紹了一種不同的 function call 方式,希望大家有所收藏。