TC39是 Ecma International标准化组织旗下的技术委员会的一员,它负责管理着ECMAScript语言和标准化API。ECMAScript语言和标准化API又可以分为两个标准:1 e+ H1 I2 I! W$ B9 h6 a
第一个是ECMA-262标准,它包含了语言的语法和核心的API。 另一个标准ECMA-402则包含了一些国际化的API,提供给ECMAScript核心API选择性支持。- s% W9 ]9 w. H8 u$ D
一、.at() . _, a5 ~& j5 ~' F9 p
这是个挺不错的新语法。其他有些语言是可以用 arr[-1] 来获取数组末尾的元素,但是对于 JS 来说这是实现不了的事情。因为 [key] 对于对象来说就是在获取 key 对应的值。数组也是对象,对于数组使用 arr[-1] 就是在获取 key 为 -1 的值。% R f# A+ L Q3 z. L! ~3 n( s
由于以上原因,我们想获取末尾元素就得这样写 arr[arr.length - 1],以后有了 at 这个方法,我们就可以通过 arr.at(-1) 来拿末尾的元素了,另外同样适用类数组、字符串。6 E' y& Y; k* J1 |7 Z
// 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
7 j2 z% u3 B# [: S4 r1 |4 ]0 }% h6 f, u3 L await 都得用 async 函数包裹大家肯定都知道,这个限制导致我们不能在全局作用域下直接使用 await,必须得包装一下。有了这个提案以后,大家就可以直接在顶层写 await 了,算是一个便利性的提案。目前该提案已经进入阶段 4,板上钉钉会发布。另外其实 Chrome 近期的更新已经支持了该功能。
/ j8 ` l- n/ t }: ]
/ Z& J2 V- `6 A f% d 三、Error Cause 5 O9 G" K- P) o" ~7 ^/ o5 u0 }2 T
这个语法主要帮助我们便捷地传递Error。一旦可能出错的地方一多,实际就不清楚错误到底是哪里产生的。如果希望外部清楚的知道上下文信息的话,需要封装以下error。( q$ k5 m. r/ G$ `7 I
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 那么有了这个语法以后,就可以这样来简化代码:! S. v* k$ x/ E, g: T
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四、管道运算符 ! p8 ~8 _- e6 |1 |. @
这个语法的Star特别多,有5k多个,侧面也能说明是个受欢迎的语法,但是距离发布应该还有好久,毕竟这个提案三四年前就有了,目前还只到阶段 1。这个语法其实在其他函数式编程语言上很常见,主要是为了函数调用方便:
* r: I6 V' S8 D" E0 {6 y' D7 { let result = exclaim(capitalize(doubleSay("hello")));
result //=> "Hello, hello!"
let result = "hello"
|> doubleSay
|> capitalize
|> exclaim;
result //=> "Hello, hello!" 这只是对于单个参数的用法,其它的用法有兴趣的读者可以自行阅读提案,其中涉及到了特别多的内容,这大概也是导致推进阶段慢的原因吧。
0 a/ \: k9 ]+ c% c! [ A8 s: M+ x 五、新的数据结构:Records & Tuples ' X8 B$ B( G4 U9 L4 ^; u+ a# S$ g
这个数据结构笔者觉得发布以后会特别有用,总共新增了两种数据结构,可以通过#来声明: F5 X( \& s: T4 Y* d" }9 A
#{ x: 1, y: 2 }6 [- ~, t, F" [3 V
#[1, 2, 3, 4]
. B# H0 Y; r. q 这种数据结构是不可变的,类似 React 中为了做性能优化会引入的 immer 或者 immutable.js,其中的值只接受基本类型或者同是不可变的数据类型。+ G" Y# s. T" E3 F- f
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"]