# 写在前面
又有很长时间没有发表文章了。其实原计划定于每周发表一篇文章,刚开始觉得这样的频率还好。慢慢的觉得这样的更新效率有点频繁, 也就没在坚持。今天突然翻了翻自己的的博客, 觉着自己写的东西,虽然不是啥大作品,个人觉着还是挺不错的。做程序开发,不管再忙。博客还是得写,哪怕频率拉长一点都可以。废话不多说,开始吧。
# es新功能
# ES MODULE动态导入
标准的import 导入是静态的。会使所有被导入的模块,在加载时就会编译(无法做到,按需加载). 动态导入可以做到根据条件动态加载模块依赖. 不管是静态模块导入方式还是动态导入,不可滥用动态导入。 使用场景:
- 当静态导入的模块很明显的降低了代码的加载速度且被使用的可能性很低,或者并不需要马上使用它。
- 当静态导入的模块很明显的占用了大量系统内存且被使用的可能性很低。
- 当被导入的模块,在加载时并不存在,需要异步获取
- 当导入模块的说明符,需要动态构建。(静态导入只能使用静态说明符)
- 当被导入的模块有副作用(这里说的副作用,可以理解为模块中会直接运行的代码),这些副作用只有在触发了某些条件才被需要时。(原则上来说,模块不能有副作用,但是很多时候,你无法控制你所依赖的模块的内容)
使用: 动态导入使用import关键字, 使用时类似函数调用,调用 import(module-path)。其中的参数表明是模块所在路径。 以这种方式使用。将会以pormise返回.
// main
if(window){
import('./my-module.js').then(module => {
console.log(module.a)
})
}else{
console.log('now is not browser runtime')
}
// my-module
export const a = 2;
执行 main,结果返回main:a
# 空值合并运算符
作用: 为变量赋予默认值. 默认值设置,比较常见就是 使用 || (or)运算符. 该运算符是双目运算符
pattern: leftexptr ?? right-exptr --NOTE:--当左侧操作数值为 null 或 undefined时, 表达式值为右侧值; 否则为左侧操作数值。
实践:
const nullValue = null;
const emptyText = ""; // falsy
const someNumber = 42;
const valA = nullValue ?? "default for A";
const valB = emptyText ?? "default for B";
const valC = someNumber ?? 0;
console.log(valA); // "default for A"
console.log(valB); // "" (as the empty string is not null or undefined)
console.log(valC); // 42
# 可选链接运算符(optional chaining)
引用嵌套对象属性,而不用考虑属性是否存在。 使用可选链接运算符 ?. 与字面量属性结合 如果不存在,返回undefined; 函数结果也返回undefined. 实践:
const user = { name: "John" };
// Fails with `Uncaught TypeError: Cannot read property 'city' of undefined`
const city = user.address.city;
// Works but verbose
let city = "Not Set";
if (user.address !== undefined && user.address !== null) {
city = user.address.city;
}
// Works and concise but requires a 3rd party library
const city = _.get(user, "address.city", "Not Set");
// 🤗
const city = user?.address?.city ?? "Not Set";
# BigInt
javascrip的tnumber可表示最大范围是 2^53-1.现在提供bitInt方法可表示大与边界的数.
const hugeString = BigInt("9007199254740991")
// ↪ 9007199254740991n
const hugeHex = BigInt("0x1fffffffffffff")
// ↪ 9007199254740991n
const hugeBin = BigInt("0b11111111111111111111111111111111111111111111111111111")
// ↪ 9007199254740991n
// 类型
let a = 2n
typeof(a) // bigint
# globalThis
全局globalThis属性包含this类似于全局对象的全局值。而不用针对特定平台hack。在之前获取全局对象,
var getGlobal = function () {
if (typeof self !== 'undefined') { return self; }
if (typeof window !== 'undefined') { return window; }
if (typeof global !== 'undefined') { return global; }
throw new Error('unable to locate global object');
};
var globals = getGlobal();
if (typeof globals.setTimeout !== 'function') {
// no setTimeout in this environment!
}