一、私有属性
ES10 在类属性前面加 #
表示私有属性,并且需要提前声明,私有属性只有在内部才能调用。
class Person {
#age;
#weight;
constructor(name, age, weight) {
this.name = name;
this.#age = age;
this.#weight = weight;
}
intro() {
console.log(this.#age);
console.log(this.#weight);
}
}
let girl = new Person('lily', 18, '45kg');
girl.intro(); // 返回 18 45kg
console.log(girl.age); // 返回 undefined
二、Promise 扩展
Promise.allSettled()
方法接受 Promise 数组,返回的结果也是 Promise 对象,返回的结果永远是成功状态,成功的值是每个 Promise 的状态和结果。
const p1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('商品数据 - 1');
}, 1000);
})
const p2 = new Promise((resolve, reject) => {
setTimeout(() => {
// resolve('商品数据 - 2');
reject('出错啦');
}, 1000);
})
const result = Promise.allSettled([p1, p2]);
console.log(result);
Promise.allSettled()
和 Promise.all()
相似,都用来做批量异步任务的操作,Promise.all()
只有所有 Promise 成功返回的才成功。
三、字符串扩展
String.matchAll()
方法用来得到正则批量匹配的结果,返回的是可迭代对象。
let str = `
<ul>
<li>
<a>肖申克的救赎</a>
<p>上映时间:1994-09-10</p>
</li>
<li>
<a>阿甘正传</a>
<p>上映时间:1994-07-06</p>
</li>
</ul>`;
const reg = /<li>.*?<a>(.*?)<\/a>.*?<p>(.*?)<\/p>/gs;
const result = str.matchAll(reg);
console.log([...result]);
四、可选链操作符
?.
是可选链操作符,当应对对象层级较深时,用作层级判断。当前置条件符合才检查下一个属性。
function mian(config) {
const dbHost = config?.db?.host;
console.log(dbHost);
}
mian({
db: {
host: '192.168.1.100',
username: 'root'
},
cache: {
host: '192.168.1.200',
username: 'root'
}
})
// 返回 192.168.1.100
五、动态 import 加载
ES6 的模块化是一个静态的模块系统,动态 import 实现按需加载。
import() 函数返回结果是一个 Promise 对象,成功的值就是模块里暴露处理的对象。
const btn = document.querySelector('button');
btn.onclick = function() {
// 动态引入
import ('./hello.js').then(module => {
module.hello();
})
}
六、BigInt
ES11 引入新的数据类型 BigInt,表示大整数,用来进行更大的数值运算。
1. 定义大整型
在普通整型后面加 n
。
let n = 521n;
console.log(n, typeof n); // 521n bigint
let n1 = 123;
console.log(BigInt(n1)); // 123n
2. 大数值运算
大整型只能和大整型进行运算。
let max = Number.MAX_SAFE_INTEGER;
console.log(BigInt(max) + BigInt(2));
七、globalthis
globalthis
始终指向全局对象,如果需要对全局对象进行操作,直接调用 globalthis
。