ES2022 发布,6 个新增小功能
1、正则表达式匹配索引 /d
新增匹配标示符号 /d ,返回匹配项的起始和终点的下标。返回值为一个二维数组。 使用:
const expr = /a+(?<B>b+)+c/d
const result = expr.exec("aaabbbc")
console.log(result.indices)
// [[0, 7], [3, 6], groups:{[3, 6]}]
console.log(result.indices.groups['B'])
// [3,6]
2、数组查找 .at()
.at() 输入参数为数组下标,返回对应下标位置的值。
const array = [3,2,4,5,6,7]
array.at(0) // 3
array[0] // 3
array.at(-1) // 7
array.at(-2) // 6
array.at(-6) // 3
array.at(-7) // undefined
3、可访问的 Object.prototype.hasOwnProperty
Object 原型上新增 hasOwn() 方法,用于直接访问 Object.prototype.hasOwnProperty 方法。 使用:
// 之前 javascript
const x = { job: "frontend" }
const hasOwnProperty = Object.prototype.hasOwnProperty
if (hasOwnProperty.call(x, "foo")) {
console.log(1111)
}
// 1111
// 使用 hasOwn() 后:
const x = { job: "frontend" }
if (Object.hasOwn(x, "foo")) {
console.log(222)
}
// 222
4、Class Fields
在 Class 类方法中,将 # 字符添加到我们的变量声明中创建私有字段。在此版本之前,没有适当的方法来创建私有字段,通过使用提升有一些方法可以解决它。
class Calculator {
#num = 0
add() {
this.#num++
}
subtraction() {
this.#num--
}
}
const o = new Calculator()
o.#num // Uncaught SyntaxError: Private field '#num' must be declared in an enclosing class
o.increment() // Uncaught TypeError: o.increment is not a function
o.logIteration() // Uncaught TypeError: o.increment is not a function
从执行结果可以看出,我们无法从外界访问类中私有变量。
5、Class Static Block
作为新规范的一部分,我们现在可以在任何类中包含静态块,它们将只运行一次,并且是装饰或执行类静态端的某些字段初始化的好方法。 我们不限于使用一个块,我们可以拥有尽可能多的块。
class A {
static {
console.log('one')
}
static {
console.log('two')
}
static {
console.log('three')
}
}
// one
// two
// three
静态块使得我们访问私有变量/私有字段成为可能。例如,我们可以在静态块中定义 getPrivateField 获取私有变量 #privateField 的值:
let getPrivateField
class Foo {
#privateField
constructor(x) {
this.#privateField = x
}
static {
getPrivateField = (o) => o.#privateField
}
}
const a = new Foo('恭喜你!你拿到了私有变量 #privateField 的值')
console.log(getPrivateField(a)) // 恭喜你!你拿到了私有变量 #privateField 的值
6、Private Fields
新的私有字段是一个很棒的功能,但是,在某些静态方法中检查字段是否为私有可能会变得很方便。
尝试在类范围之外调用它会导致我们之前看到的相同错误。
class Bookshelf {
#books
static list(obj) {
return #books in obj
}
}
const b = new Bookshelf()
Bookshelf.list(b)
Bookshelf.list({})
#books in b
// Uncaught SyntaxError: Private field '#books' must be declared in an enclosing class
更多内容查看:github.com/tc39/propos…