『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
本文插图
可选链运算符 截至目前 , 在搜索某个对象内部深入嵌套的属性值时 , 或者使用返回对象或/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
本文插图
‘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 ? ???♂?
本文插图
动态import 目前从./module导入模块的形式是静态的 , 只接受字符串文字 , 也仅作为链接过程在运行前起效 。
动态的 import(...)允许开发者在运行时动态载入部分JS应用 , 相对于目前的导入方式有着一系列优势:
- 加载用户语言 , 而不是全部加载
- 延迟加载应用程序的路径 , 从而提高性能
推荐阅读
- 好物研究院@官方种草!本周应用推荐来了
- 「马蜂窝」马蜂窝等OTA平台实录:一边在线“劝退” 一边直播“种草”
- 「驱动之家」高颜值一眼种草!华硕 adolbook14 2020 千禧粉图赏
- [直播]专访“种草女王”黎贝卡:“直播很火,我觉得不用急”
- [青眼]估值50亿美元,“种草”社区头牌,小红书如何走出商业化迷途?
- @高颜值第一眼就种草!adolbook14 2020笔记本评测
- 「」大师设计索尼 PS5 渲染图 网友:白色款种草了
- 『』一顿操作猛如虎 华为MateXs高效办公神技瞬间种草
- [函数式]JavaScript面试问题:函数式编程
- 小红书@“种草”社区头牌小红书,如何走出商业化迷途?
