ECMASript 11新特性
ES11语法新特性
私有属性
class Person {
//公有属性
name;
//私有属性
#age;
#weight;//构造方法
constructor(name, age, weight) {
this.name = name;
this.#age = age;
this.#weight = weight;
}
intro() {
console.log(girl.name);
console.log(girl.#age);
console.log(girl.#weight);
}
}
//实例化
const girl = new Person('小红', 18, '45kg');
// console.log(girl.name);
// console.log(girl.#age);
// console.log(girl.#weight);
//无法在类的外部直接调用
//Uncaught SyntaxError: Private field '#age' must be declared in an enclosing class
girl.intro();//可以通过内部方法进行调用
Promise.allSettled
//声明两个promise对象
const p1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('商品数据-1');
}, 1000)
});
const p2 = new Promise((resolve, reject) => {
setTimeout(() => {
//resolve('商品数据-2');
reject('出错啦!');
}, 1000)
});
//调用 allsettled 方法
//可以检测所有对象的promise的成功和失败
// const result = Promise.allSettled([p1,p2]);
//全部成功才会返回成功的promise
const res = Promise.all([p1,p2])
console.log(res);
String.prototype.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>/sg;
//调用方法
//用来得到正则批量匹配的结果
const result = str.matchAll(reg);
// for( let v of result){
// console.log(v);
// }
const arr = [...result];
console.log(arr);
可选链操作符
// const dbHost = config && config.db && config.db.host;
//当检测前面参数传入以后再往后进行
const dbHost = config?.db?.host;
console. log(dbHost);
}
main({
db: {
host: ' 192.168.1.100',
username: 'root',
},
cache: {
host: '192.168.1.200',
username: 'admin',
}
})
动态import
在需要的时候再引入,可以减少运算
<body>
<script src="./app.js" type="module"></script>
<button id="btn">按钮</button>
</body>
// import * as mq from "./hello"
//获取元素
const btn = document.getElementById( 'btn' );
btn.onclick = function(){
import( './hello' ).then(module => {
module.hello();
});
}
function hello() {
alert(hello);
}
数据类型BigInt
//大整形
let n = 521n;
console.log(n, typeof (n));
let n2 = 123;
console.log(BigInt(n2));
//console.log(BigInt(3.1415926));//不支持浮点运算
//大数值运算
let max = Number.MAX_SAFE_INTEGER;
console.log(max);
console.log(max + 1);
console.log(max + 2);
console.log(BigInt(max))
console.log(BigInt(max) + BigInt(1));
console.log(BigInt(max) + BigInt(2))
特殊变量globalThis
支持JS和Node,js
无论执行环境是什么,始终都指向全局对象