新聞中心
TC39 的提案筆者一直有關(guān)注,攢了一些有趣的今天來聊聊。

蘭考網(wǎng)站建設(shè)公司創(chuàng)新互聯(lián)公司,蘭考網(wǎng)站設(shè)計制作,有大型網(wǎng)站制作公司豐富經(jīng)驗。已為蘭考超過千家提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\外貿(mào)網(wǎng)站建設(shè)要多少錢,請找那個售后服務(wù)好的蘭考做網(wǎng)站的公司定做!
PS:提案總共五個階段,只有到階段 4 才會被納入到發(fā)布規(guī)范中,其它的只是有幾率會被納入。
.at()
這是個挺不錯的新語法。其他有些語言是可以用 arr[-1] 來獲取數(shù)組末尾的元素,但是對于 JS 來說這是實現(xiàn)不了的事情。因為 [key] 對于對象來說就是在獲取 key 對應(yīng)的值。數(shù)組也是對象,對于數(shù)組使用 arr[-1] 就是在獲取 key 為 -1 的值。
由于以上原因,我們想獲取末尾元素就得這樣寫 arr[arr.length - 1],以后有了 at 這個方法,我們就可以通過 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ù)包裹大家肯定都知道,這個限制導(dǎo)致我們不能在全局作用域下直接使用 await,必須得包裝一下。
有了這個提案以后,大家就可以直接在頂層寫 await 了,算是一個便利性的提案。
目前該提案已經(jīng)進(jìn)入階段 4,板上釘釘會發(fā)布。另外其實 Chrome 近期的更新已經(jīng)支持了該功能。
image-20210620162451146
Error Cause
這個語法主要幫助我們便捷地傳遞 Error。一旦可能出錯的地方一多,我們實際就不清楚錯誤到底是哪里產(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
那么有了這個語法以后,我們可以這樣來簡化代碼:
- 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
管道運算符
這個語法的 Star 特別多,有 5k 多個,側(cè)面也能說明是個受歡迎的語法,但是距離發(fā)布應(yīng)該還有好久,畢竟這個提案三四年前就有了,目前還只到階段 1。
這個語法其實在其他函數(shù)式編程語言上很常見,主要是為了函數(shù)調(diào)用方便:
- let result = exclaim(capitalize(doubleSay("hello")));
- result //=> "Hello, hello!"
- let result = "hello"
- |> doubleSay
- |> capitalize
- |> exclaim;
- result //=> "Hello, hello!"
這只是對于單個參數(shù)的用法,其它的用法有興趣的讀者可以自行閱讀提案,其中涉及到了特別多的內(nèi)容,這大概也是導(dǎo)致推進(jìn)階段慢的原因吧。
新的數(shù)據(jù)結(jié)構(gòu):Records & Tuples
這個數(shù)據(jù)結(jié)構(gòu)筆者覺得發(fā)布以后會特別有用,總共新增了兩種數(shù)據(jù)結(jié)構(gòu),我們可以通過 # 來聲明:
1. #{ x: 1, y: 2 }2.#[1, 2, 3, 4]
這種數(shù)據(jù)結(jié)構(gòu)是不可變的,類似 React 中為了做性能優(yōu)化會引入的 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 中尋找。
分享名稱:這些 JS 的新語法有點東西啊
URL分享:http://m.fisionsoft.com.cn/article/coiepph.html


咨詢
建站咨詢
