你需要了解的 7 个令人兴奋的 JavaScript 新功能
本文已由@rana_kualu翻译成日语,网址:https://qiita.com/rana_kualu/items/ee7694aa1cd4ae7f4483
JavaScript(或 ECMA Script)是一门不断发展的语言,围绕其未来的发展提出了许多提案和想法。TC39(技术委员会 39)是负责定义 JS 标准和特性的委员会,今年他们非常活跃。以下是目前处于“第 3 阶段”的一些提案的摘要,该阶段是“完成”前的最后一个阶段。这意味着这些特性应该很快就会在浏览器和其他引擎中实现。事实上,其中一些已经可用。
1. 私有字段#
适用于 Chrome 和 NodeJS 12
是的,你没看错。JS 终于可以在类中获取私有字段了。再也不用this._doPrivateStuff()
定义闭包来存储私有值,或者用它WeakMap
破解私有 props 了。
语法如下
// private fields must start with '#'
// and they can't be accessed outside the class block
class Counter {
#x = 0;
#increment() {
this.#x++;
}
onClick() {
this.#increment();
}
}
const c = new Counter();
c.onClick(); // works fine
c.#increment(); // error
提案:https://github.com/tc39/proposal-class-fields
2. 可选链式调用?.
你是否曾经需要访问对象内部嵌套几层的属性,并遇到了臭名昭著的错误Cannot read property 'stop' of undefined
?然后你修改代码来处理undefined
嵌套链中所有可能的对象,例如:
const stop = please && please.make && please.make.it && please.make.it.stop;
// or use a library like 'object-path'
const stop = objectPath.get(please, "make.it.stop");
使用可选链,你很快就能完成同样的操作:
const stop = please?.make?.it?.stop;
提案:https://github.com/tc39/proposal-optional-chaining
3. 空值合并??
变量有一个可选值,可以缺失,如果缺失则使用默认值,这种情况很常见
const duration = input.duration || 500;
问题在于||
它将覆盖所有虚假值,如(0
,, ) ''
,false
而这些虚假值在某些情况下可能是有效输入。
输入空值合并运算符,它仅覆盖undefined
或null
const duration = input.duration ?? 500;
提案:https://github.com/tc39/proposal-nullish-coalescing
4. BigInt1n
适用于 Chrome 和 NodeJS 12
JS 数学一直很差的原因之一是我们无法可靠地存储大于 的数字2 ^ 53
,这使得处理相当大的数字变得非常困难。幸运的是,BigInt
有一个提案可以解决这个问题。
无需多言
// can define BigInt by appending 'n' to a number literal
const theBiggestInt = 9007199254740991n;
// using the constructor with a literal
const alsoHuge = BigInt(9007199254740991);
// or with a string
const hugeButString = BigInt('9007199254740991');
BigInt
你也可以像对普通数字那样使用相同的运算符,例如:,,,,,,……+
不过有个小问题,大多数运算中不能与数字混合使用。比较和可以,但加法不行-
。/
*
%
BigInt
Number
BigInt
1n < 2
// true
1n + 2
// 🤷♀️ Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions
提案:https://github.com/tc39/proposal-bigint
5.static
字段
适用于 Chrome 和 NodeJS 12
这个很简单。它允许在类中使用静态字段,类似于大多数 OOP 语言。静态字段可以作为枚举的替代品,并且也可以与私有字段一起使用。
class Colors {
// public static fields
static red = '#ff0000';
static green = '#00ff00';
// private static fields
static #secretColor = '#f0f0f0';
}
font.color = Colors.red;
font.color = Colors.#secretColor; // Error
提案:https://github.com/tc39/proposal-static-class-features
6. 顶级await
Chrome 版本可用
允许你在代码顶层使用 await。这对于fetch
在浏览器控制台中调试异步内容(例如 )非常有用,无需将其包装在异步函数中。
如果您需要复习一下 async 和 await,请查看我在这里解释它的文章
另一个绝佳用例是,它可以在以异步方式初始化的 ES 模块的顶层使用(想象一下数据库层建立连接)。当导入这样的“异步模块”时,模块系统会等待它解析后再执行依赖它的模块。这将使处理异步初始化比当前返回初始化承诺并等待它的解决方法更加容易。模块将不知道其依赖项是否是异步的。
// db.mjs
export const connection = await createConnection();
// server.mjs
import { connection } from './db.mjs';
server.start();
server.mjs
在此示例中,在 中连接完成之前,不会执行任何操作db.mjs
。
提案:https://github.com/tc39/proposal-top-level-await
7.WeakRef
适用于 Chrome 和 NodeJS 12
对象的弱引用是指不足以维持对象存活的引用。每当我们用(const
、let
、var
)创建一个变量时,只要该变量的引用仍然可访问,垃圾回收器 (GC) 就永远不会从内存中删除该变量。这些都是强引用。然而,如果没有强引用指向弱引用的对象,GC 可能会随时删除它。WeakRef
实例有一个方法deref
,可以返回引用的原始对象,或者undefined
返回原始对象是否已被回收。
这可能对于缓存廉价对象很有用,因为您不想将它们全部永远存储在内存中。
const cache = new Map();
const setValue = (key, obj) => {
cache.set(key, new WeakRef(obj));
};
const getValue = (key) => {
const ref = cache.get(key);
if (ref) {
return ref.deref();
}
};
// this will look for the value in the cache
// and recalculate if it's missing
const fibonacciCached = (number) => {
const cached = getValue(number);
if (cached) return cached;
const sum = calculateFibonacci(number);
setValue(number, sum);
return sum;
};
这对于缓存远程数据可能不是一个好主意,因为它可能会以不可预测的方式从内存中删除。在这种情况下,最好使用类似 LRU 缓存之类的缓存。
提案:https://github.com/tc39/proposal-weakrefs
就是这样。希望你和我一样对这些酷炫的新功能感到兴奋。想了解更多关于这些提案以及我未提及的其他提案的详细信息,请关注 GitHub 上的 TC39 提案。
文章来源:https://dev.to/gafi/7-new-exciting-javascript-features-you-need-to-know-1fkh