『JavaScript』种草 ES2020 八大新功能( 二 )


【『JavaScript』种草 ES2020 八大新功能】给属性名称加上#前缀 , 就表示此字段是私有字段 , 不对外公开 。 下面请看示例:
class Counter {#x = 0; increment {this.#x++;}getNum{return this.#x;}}const counter = new Counter;console.log(counter.#x);// Uncaught SyntaxError: Private field '#x' must be declared in an enclosing class counter.increment; // Worksconsole.log(counter.getNum); // 1 『JavaScript』种草 ES2020 八大新功能
本文插图

可选链运算符 截至目前 , 在搜索某个对象内部深入嵌套的属性值时 , 或者使用返回对象或/undefined的API时 , 通常用以下方式来检查中间值:
// Checking for intermediate nodes:const deeplyNestedValue = http://news.hoteastday.com/a/obj && obj.prop1 && obj.prop1.prop2;// Checking if the node exists in the DOM:const fooInputEl = document.querySelector('input[name=foo]');const fooValue = http://news.hoteastday.com/a/fooInputEl && fooInputEl.value; 可选链运算符则允许我们更简单地处理许多情况 。 重写上面的示例将获得以下代码:
// Checking for intermediate nodes:const deeplyNestedValue = http://news.hoteastday.com/a/obj?.prop1?.prop2;// Checking if the node exists in the DOM:const fooValue = document.querySelector('input[name=foo]')?.value; 可选链运算符是一个短路计算操作 , 即当左侧?.检查到或undefined时 , 就会停止表达式的运行:
// x is incremented if and only if 'a' is notor undefineda?.[++x] 可选链可与函数一并使用:
func?.(...args) // optional function or method call

『JavaScript』种草 ES2020 八大新功能
本文插图

‘BigInt’ 我们已经用Number来表示JS中的数字 , 问题在于最大的数字是2?3 , 再往上的数字就不可靠了 。
const x = Number.MAX_SAFE_INTEGER; // 9007199254740991const y = x + 1; // 9007199254740992 ? equal to 2^53const z = x + 2; // 9007199254740992 ? well, it's broken BigInt提供了一种方法 , 来表示大于2?3的数字 。 通过在整数末尾添加n来创建:
const aBigInteger = 9007199254740993n;// There is also a constructor:const evenBigger = BigInt(9007199254740994); // 9007199254740994nconst fromString = BigInt("9007199254740995"); // 9007199254740995n BigInt通常的操作与数字相同 , 但不能在运算中一同使用:
let sum = 1n + 2, multiplication = 1n * 2;// TypeError: Cannot mix BigInt and other types, use explicit conversions 可使用构造函数Number将BigInt转化为Number , 但在某些情况下可能会失去精度 。 因此 , 建议仅在代码中相应预期数值较大时再使用BigInt 。
Number(900719925474099267n); // 900719925474099300 ? ???♂?

『JavaScript』种草 ES2020 八大新功能
本文插图

动态import 目前从./module导入模块的形式是静态的 , 只接受字符串文字 , 也仅作为链接过程在运行前起效 。
动态的 import(...)允许开发者在运行时动态载入部分JS应用 , 相对于目前的导入方式有着一系列优势: