這些 JS 的新語法有點(diǎn)東西啊
TC39 的提案筆者一直有關(guān)注,攢了一些有趣的今天來聊聊。
PS:提案總共五個(gè)階段,只有到階段 4 才會(huì)被納入到發(fā)布規(guī)范中,其它的只是有幾率會(huì)被納入。
.at()
這是個(gè)挺不錯(cuò)的新語法。其他有些語言是可以用 arr[-1] 來獲取數(shù)組末尾的元素,但是對(duì)于 JS 來說這是實(shí)現(xiàn)不了的事情。因?yàn)?[key] 對(duì)于對(duì)象來說就是在獲取 key 對(duì)應(yīng)的值。數(shù)組也是對(duì)象,對(duì)于數(shù)組使用 arr[-1] 就是在獲取 key 為 -1 的值。
由于以上原因,我們想獲取末尾元素就得這樣寫 arr[arr.length - 1],以后有了 at 這個(gè)方法,我們就可以通過 arr.at(-1) 來拿末尾的元素了,另外同樣適用類數(shù)組、字符串。
- // Polyfill
- function at(n) {
- // ToInteger() abstract op
- n = Math.trunc(n) || 0;
- // Allow negative indexing from the end
- if(n < 0) n += this.length;
- // OOB access is guaranteed to return undefined
- if(n < 0 || n >= this.length) return undefined;
- // Otherwise, this is just normal property access
- return this[n];
- }
頂層 await
await 都得用 async 函數(shù)包裹大家肯定都知道,這個(gè)限制導(dǎo)致我們不能在全局作用域下直接使用 await,必須得包裝一下。
有了這個(gè)提案以后,大家就可以直接在頂層寫 await 了,算是一個(gè)便利性的提案。
目前該提案已經(jīng)進(jìn)入階段 4,板上釘釘會(huì)發(fā)布。另外其實(shí) Chrome 近期的更新已經(jīng)支持了該功能。
image-20210620162451146
Error Cause
這個(gè)語法主要幫助我們便捷地傳遞 Error。一旦可能出錯(cuò)的地方一多,我們實(shí)際就不清楚錯(cuò)誤到底是哪里產(chǎn)生的。如果希望外部清楚的知道上下文信息的話,我們需要封裝以下 error。
- async function getSolution() {
- const rawResource = await fetch('//domain/resource-a')
- .catch(err => {
- // How to wrap the error properly?
- // 1. throw new Error('Download raw resource failed: ' + err.message);
- // 2. const wrapErr = new Error('Download raw resource failed');
- // wrapErr.cause = err;
- // throw wrapErr;
- // 3. class CustomError extends Error {
- // constructor(msg, cause) {
- // super(msg);
- // this.cause = cause;
- // }
- // }
- // throw new CustomError('Download raw resource failed', err);
- })
- const jobResult = doComputationalHeavyJob(rawResource);
- await fetch('//domain/upload', { method: 'POST', body: jobResult });
- }
- await doJob(); // => TypeError: Failed to fetch
那么有了這個(gè)語法以后,我們可以這樣來簡(jiǎn)化代碼:
- async function doJob() {
- const rawResource = await fetch('//domain/resource-a')
- .catch(err => {
- throw new Error('Download raw resource failed', { cause: err });
- });
- const jobResult = doComputationalHeavyJob(rawResource);
- await fetch('//domain/upload', { method: 'POST', body: jobResult })
- .catch(err => {
- throw new Error('Upload job result failed', { cause: err });
- });
- }
- try {
- await doJob();
- } catch (e) {
- console.log(e);
- console.log('Caused by', e.cause);
- }
- // Error: Upload job result failed
- // Caused by TypeError: Failed to fetch
管道運(yùn)算符
這個(gè)語法的 Star 特別多,有 5k 多個(gè),側(cè)面也能說明是個(gè)受歡迎的語法,但是距離發(fā)布應(yīng)該還有好久,畢竟這個(gè)提案三四年前就有了,目前還只到階段 1。
這個(gè)語法其實(shí)在其他函數(shù)式編程語言上很常見,主要是為了函數(shù)調(diào)用方便:
- let result = exclaim(capitalize(doubleSay("hello")));
- result //=> "Hello, hello!"
- let result = "hello"
- |> doubleSay
- |> capitalize
- |> exclaim;
- result //=> "Hello, hello!"
這只是對(duì)于單個(gè)參數(shù)的用法,其它的用法有興趣的讀者可以自行閱讀提案,其中涉及到了特別多的內(nèi)容,這大概也是導(dǎo)致推進(jìn)階段慢的原因吧。
新的數(shù)據(jù)結(jié)構(gòu):Records & Tuples
這個(gè)數(shù)據(jù)結(jié)構(gòu)筆者覺得發(fā)布以后會(huì)特別有用,總共新增了兩種數(shù)據(jù)結(jié)構(gòu),我們可以通過 # 來聲明:
1. #{ x: 1, y: 2 }2.#[1, 2, 3, 4]
這種數(shù)據(jù)結(jié)構(gòu)是不可變的,類似 React 中為了做性能優(yōu)化會(huì)引入的 immer 或者 immutable.js,其中的值只接受基本類型或者同是不可變的數(shù)據(jù)類型。
- const proposal = #{
- id: 1234,
- title: "Record & Tuple proposal",
- contents: `...`,
- // tuples are primitive types so you can put them in records:
- keywords: #["ecma", "tc39", "proposal", "record", "tuple"],
- };
- // Accessing keys like you would with objects!
- console.log(proposal.title); // Record & Tuple proposal
- console.log(proposal.keywords[1]); // tc39
- // Spread like objects!
- const proposal2 = #{
- ...proposal,
- title: "Stage 2: Record & Tuple",
- };
- console.log(proposal2.title); // Stage 2: Record & Tuple
- console.log(proposal2.keywords[1]); // tc39
- // Object functions work on Records:
- console.log(Object.keys(proposal)); // ["contents", "id", "keywords", "title"]
最后
以上筆者列舉了一部分有意思的 TC39 提案,除了以上這些還有很多提案,各位讀者有興趣的話可以在 TC39 中尋找。