• ES13的11个超赞的新属性


    像其他语言一样,JavaScript也在不断迭代和进化。JS每年都会加入很多新的功能来让自己变得越发强大,也正是这样,我们开发者才能写出更加表意和准确的代码。

    在这篇文章中我们会通过一些例子来看一下最新的ECMAScript 2022(ES13)给我们开发者带来的11个超赞的新功能。

    1. 类成员声明

    在ES13之前,我们只能在构造函数里面声明类的成员,而不能像其他大多数语言一样在类的最外层作用域里面声明成员:

    1. class Car {
    2. constructor() {
    3. this.color = 'blue';
    4. this.age = 2;
    5. }
    6. }
    7. const car = new Car();
    8. console.log(car.color); // blue
    9. console.log(car.age); // 2

    老实说这么写起来挺不方便的,不过ES13出来之后,这都不算什么事儿了。现在我们终于可以突破这个限制,写下面这样的代码了:

    1. class Car {
    2. color = 'blue';
    3. age = 2;
    4. }
    5. const car = new Car();
    6. console.log(car.color); // blue
    7. console.log(car.age); // 2

    2. 给类定义私有方法和成员变量

    ES13之前,我们是不可能给类定义私有成员的。所以一些程序员为了表示某个成员变量是一个私有属性,会给该属性名添加一个下划线(_)作为后缀。可是这只能作为程序员之间的君子之约来使用,因为这些变量其实还是可以被外界访问到的。

    1. class Person {
    2. _firstName = 'Joseph';
    3. _lastName = 'Stevens';
    4. get name() {
    5. return `${this._firstName} ${this._lastName}`;
    6. }
    7. }
    8. const person = new Person();
    9. console.log(person.name); // Joseph Stevens
    10. // 这些所谓的私有属性其实还是可以被外界访问到的
    11. console.log(person._firstName); // Joseph
    12. console.log(person._lastName); // Stevens
    13. // 而且还能被改来改去
    14. person._firstName = 'Robert';
    15. person._lastName = 'Becker';
    16. console.log(person.name); // Robert Becker

    不过ES13出来后,妈妈再也不用怕我们的私有属性会被别人访问和更改了。在ES13中,我们只需要给我们的属性名添加一个hashtag(#)前缀,这个属性就变成私有的了。当我们的属性变为私有后,任何外界对其的访问都会出错哦。

    1. class Person {
    2. #firstName = 'Joseph';
    3. #lastName = 'Stevens';
    4. get name() {
    5. return `${this.#firstName} ${this.#lastName}`;
    6. }
    7. }
    8. const person = new Person();
    9. console.log(person.name);
    10. // SyntaxError: Private field '#firstName' must be
    11. // declared in an enclosing class
    12. console.log(person.#firstName);
    13. console.log(person.#lastName);

    这里值得一提的是,上面说的SyntaxError是一个编译时抛出的错误,所以你不会等你的代码运行后才知道这个属性被非法访问了。

    3. 支持在最外层写await

    我们都知道在JS中,await操作符的作用就是当我们碰到一个promise的时候,我们可以使用await来暂停当前代码的执行,等到这个promise被settled(fulfilled或者rejected)了,我们才继续当前代码的执行。

    可是之前使用await的时候有个很头疼的地方就是一定要在一个async的函数里面使用而不能在全局作用域里面使用,像下面这么写就会报错:

    1. function setTimeoutAsync(timeout) {
    2. return new Promise((resolve) => {
    3. setTimeout(() => {
    4. resolve();
    5. }, timeout);
    6. });
    7. }
    8. // SyntaxError: await is only valid in async functions
    9. await setTimeoutAsync(3000);

    ES13出来后,就舒服多了,我们终于可以这么写代码了:

    1. function setTimeoutAsync(timeout) {
    2. return new Promise((resolve) => {
    3. setTimeout(() => {
    4. resolve();
    5. }, timeout);
    6. })
    7. }
    8. // 慢慢地等时间流逝吧
    9. await setTimeoutAsync(3000);

    4. 类支持定义静态成员和静态私有方法

    在ES13中,我们还可以给类定义静态成员和静态私有函数。类的静态方法可以使用this关键字访问其他的私有或者公有静态成员,而对于类的实例方法则可以通过this.constructor来访问这些静态属性.

    1. class Person {
    2. static #count = 0;
    3. static getCount() {
    4. return this.#count;
    5. }
    6. constructor() {
    7. this.constructor.#incrementCount();
    8. }
    9. static #incrementCount() {
    10. this.#count++;
    11. }
    12. }
    13. const person1 = new Person();
    14. const person2 = new Person();
    15. console.log(Person.getCount()); // 2

    5. 类支持定义静态代码块

    ES13允许在类中通过static关键字定义一系列静态代码块,这些代码块只会在类被创造的时候执行一次。这其实有点像一些其他的如C#和Java等面向对象的编程语言的静态构造函数的用法。

    一个类可以定义任意多的静态代码块,这些代码块会和穿插在它们之间的静态成员变量一起按照定义的顺序在类初始化的时候执行一次。我们还可以使用super关键字来访问父类的属性。

    1. class Vehicle {
    2. static defaultColor = 'blue';
    3. }
    4. class Car extends Vehicle {
    5. static colors = [];
    6. static {
    7. this.colors.push(super.defaultColor, 'red');
    8. }
    9. static {
    10. this.colors.push('green');
    11. }
    12. console.log(Car.colors); ['blue', 'red', 'green']
    13. }

    6. 使用in来判断某个对象是否拥有某个私有属性

    这个新属性的名字其实叫做Ergonomic Brand Checks for Private Fields,原谅我才疏学浅,我实在不知道怎么翻译,所以大概将它的作用表达了出来。总的来说,它就是用来判断某个对象是否拥有某个特定的私有属性,是通过in操作符来判断的。

    1. class Car {
    2. #color;
    3. hasColor() {
    4. return #color in this;
    5. }
    6. }
    7. const car = new Car();
    8. console.log(car.hasColor()); // true

    这个in操作符甚至还可以区分不同类的同名私有属性:

    1. class Car {
    2. #color;
    3. hasColor() {
    4. return #color in this;
    5. }
    6. }
    7. class House {
    8. #color;
    9. hasColor() {
    10. return #color in this;
    11. }
    12. }
    13. const car = new Car();
    14. const house = new House();
    15. console.log(car.hasColor()); // true
    16. console.log(car.hasColor.call(house)); // false
    17. console.log(house.hasColor()); // true
    18. console.log(house.hasColor.call(car)); // false

    7. 使用at函数来索引元素

    一般来说如果我们想要访问数组的第N个元素,我们会使用方括号[N - 1]:

    1. const arr = ['a', 'b', 'c', 'd'];
    2. console.log(arr[1]); //b

    这样写大多数时候都是没有什么问题的,其他语言也是这么做的,可是当我们需要访问数组倒数第N个元素的时候,我们的代码就变得有点奇怪了:

    const arr = ['a', 'b', 'c', 'd'];
    
    // 倒数第一个元素
    console.log(arr[arr.length - 1]); // d
    
    // 倒数第二个元素
    console.log(arr[arr.length - 2]); // c

    这么看你的代码是不是一下子变丑了?不用怕,ES13的at()函数帮你写出更优雅的代码!使用新的new()方法,当我们想要访问倒数第N个元素时,我们只需要传入-Nat()即可:

    const arr = ['a', 'b', 'c', 'd'];
    
    // 倒数第一个元素
    console.log(arr.at(-1)); // d
    // 倒数第二个元素
    console.log(arr.at(-2)); // c

    你看,你的代码是不是一下子表意多了!除了数组,stringTypedArray对象也支持at()函数哦!

    1. const str = 'Coding Beauty';
    2. console.log(str.at(-1)); // y
    3. console.log(str.at(-2)); // t
    4. const typedArray = new Uint8Array([16, 32, 48, 64]);
    5. console.log(typedArray.at(-1)); // 64
    6. console.log(typedArray.at(-2)); // 48

    8. 正则表达式匹配字符串的时候支持返回开始和结束索引

    简单来说这个新属性就是允许我们告诉RegExp在返回match对象的时候,给我们返回匹配到的子字符串的开始和结束索引。

    ES13之前,我们只能获取正则表达式匹配到的子字符串的开始索引:

    1. const str = 'sun and moon';
    2. const regex = /and/;
    3. const matchObj = regex.exec(str);
    4. // [ 'and', index: 4, input: 'sun and moon', groups: undefined ]
    5. console.log(matchObj);

    ES13后,我们就可以给正则表达式添加一个d的标记来让它在匹配的时候给我们既返回匹配到的子字符串的起始位置还返回其结束位置:

    1. const str = 'sun and moon';
    2. const regex = /and/d;
    3. const matchObj = regex.exec(str);
    4. /**
    5. [
    6. 'and',
    7. index: 4,
    8. input: 'sun and moon',
    9. groups: undefined,
    10. indices: [ [ 4, 7 ], groups: undefined ]
    11. ]
    12. */
    13. console.log(matchObj);

    你看,设置完d标记后,多了一个indices的数组,里面就是匹配到的子字符串的范围了!

    9. Object.hasOwn()方法

    在JS中,我们可以使用Object.prototype.hasOwnProperty()来检查某个对象自身是否拥有某个属性:

    1. class Car {
    2. color = 'green';
    3. age = 2;
    4. }
    5. const car = new Car();
    6. console.log(car.hasOwnProperty('age')); // true
    7. console.log(car.hasOwnProperty('name')); // false

    上面的写法其实是有两个问题的。第一个问题是:Object.prototype.hasOwnProperty()这个方法是不受保护的,换句话来说就是它可以被某个类自定义的hasOwnProperty()方法覆盖掉,而自定义方法做的事情可能和Object.prototype.hasOwnProperty()做的事情完全不一样:

    1. class Car {
    2. color = 'green';
    3. age = 2;
    4. // 你看这个方法就没有告诉我们这个类的对象是不是有某个属性
    5. hasOwnProperty() {
    6. return false;
    7. }
    8. }
    9. const car = new Car();
    10. console.log(car.hasOwnProperty('age')); // false
    11. console.log(car.hasOwnProperty('name')); // false

    上面的写法第二个问题就是:当一个对象是通过Object.create(null)创建出来的具有null原型的对象时,你想在这个对象上面调用hasOwnProperty这个方法是会报错的:

    1. const obj = Object.create(null);
    2. obj.color = 'green';
    3. obj.age = 2;
    4. // TypeError: obj.hasOwnProperty is not a function
    5. console.log(obj.hasOwnProperty('color'));

    解决这个问题的一种办法就是调用Object.prototype.hasOwnProperty这个Functioncall方法:

    1. const obj = Object.create(null);
    2. obj.color = 'green';
    3. obj.age = 2;
    4. obj.hasOwnProperty = () => false;
    5. Object.prototype.hasOwnProperty.call(obj, 'color')

    hasOwnProperty需要被多次调用的时候,我们可以通过将这部分逻辑抽象成一个方法来减少重复的代码:

    1. function objHasOwnProp(obj, propertyKey) {
    2. return Object.prototype.hasOwnProperty.call(obj, propertyKey);
    3. }
    4. const obj = Object.create(null);
    5. obj.color = 'green';
    6. obj.age = 2;
    7. obj.hasOwnProperty = () => false;
    8. console.log(objHasOwnProp(obj, 'color')); // true
    9. console.log(objHasOwnProp(obj, 'name')); // false

    封装是封装了,不过看着好麻烦有木有?所以ES13诞生了一个全新的Object.hasOwn()函数来帮我们做上面这些重复的工作。这个新的内置函数接收两个参数,一个是对象,一个是属性,如果这个对象本身就有这个属性的话,这个函数就会返回true,否则就返回false

    1. const obj = Object.create(null);
    2. obj.color = 'green';
    3. obj.age = 2;
    4. obj.hasOwnProperty = () => false;
    5. console.log(Object.hasOwn(obj, 'color')); // true
    6. console.log(Object.hasOwn(obj, 'name')); // false

    10. Error对象的Cause属性

    ES13后,Error对象多了一个cause属性来指明错误出现的原因。这个属性可以帮助我们为错误添加更多的上下文信息,从而帮助使用者们更好地定位错误。这个属性是我们在创建error对象时传进去的第二个参数对象的cause属性:

    1. function userAction() {
    2. try {
    3. apiCallThatCanThrow();
    4. } catch (err) {
    5. throw new Error('New error message', { cause: err });
    6. }
    7. }
    8. try {
    9. userAction();
    10. } catch (err) {
    11. console.log(err);
    12. console.log(`Cause by: ${err.cause}`);
    13. }

    11. 数组支持逆序查找

    在JS中,我们可以使用数组的find()函数来在数组中找到第一个满足某个条件的元素。同样地,我们还可以通过findIndex()函数来返回这个元素的位置。可是,无论是find()还是findIndex(),它们都是从数组的头部开始查找元素的,可是在某些情况下,我们可能有从数组后面开始查找某个元素的需要。例如我们知道待查找的元素在比较靠后的位置,从后面开始寻找的话会有更好的性能,就像下面这个例子:

    1. const letters = [
    2. { value: 'v' },
    3. { value: 'w' },
    4. { value: 'x' },
    5. { value: 'y' },
    6. { value: 'z' },
    7. ];
    8. // 我们想要找的y元素比较靠后, 顺序查找性能不好
    9. const found = letters.find((item) => item.value === 'y');
    10. const foundIndex = letters.findIndex((item) => item.value === 'y');
    11. console.log(found); // { value: 'y' }
    12. console.log(foundIndex); // 3

    在这种情况下使用find()findIndex()也可以,就是性能差点而已。ES13出来后,我们终于有办法处理这种情况了,那就是使用新的findLast()findLastIndex()函数。这两个函数都会从数组的末端开始寻找某个满足条件的元素:

    1. const letters = [
    2. { value: 'v' },
    3. { value: 'w' },
    4. { value: 'x' },
    5. { value: 'y' },
    6. { value: 'z' },
    7. ];
    8. // 后序查找一下子快了,有木有
    9. const found = letters.findLast((item) => item.value === 'y');
    10. const foundIndex = letters.findLastIndex((item) => item.value === 'y');
    11. console.log(found); // { value: 'y' }
    12. console.log(foundIndex); // 3

    另外一种使用findLast()findLastIndex()的场景就是我们本身就是想要寻找最后一个满足某个条件的元素,例如找到数组里面最后一个偶数,这个时候还用find()findIndex()的话得到的结果是错误的:

    1. const nums = [7, 14, 3, 8, 10, 9];
    2. // 返回了14, 结果应该是10才对
    3. const lastEven = nums.find((value) => value % 2 === 0);
    4. // 返回了1, 结果应该是4才对
    5. const lastEvenIndex = nums.findIndex((value) => value % 2 === 0);
    6. console.log(lastEven); // 14
    7. console.log(lastEvenIndex); // 1

    试想一下要得到正确的答案,我们还要使用find()findIndex()的话,要怎么改呢?首先我们需要用reverse()来反转数组,然后再调用find()findIndex()函数。不过这个做法有两个问题,一个问题就是需要改变原数组,这个问题可以通过拷贝数组来解决,占用空间多点而已。另一个问题是findIndex()得到索引后我们还要做一些额外的计算才能得到元素原数组的位置,具体做法是:

    1. const nums = [7, 14, 3, 8, 10, 9];
    2. // 在调用reverse之前先拷贝函数,以防改变原数组
    3. const reversed = [...nums].reverse();
    4. // 这次返回对了,是10
    5. const lastEven = reversed.find((value) => value % 2 === 0);
    6. // findIndex得到的结果还是不对的
    7. const reversedIndex = reversed.findIndex((value) => value % 2 === 0);
    8. // 需要多一步计算才能得出正确结果
    9. const lastEvenIndex = reversed.length - 1 - reversedIndex;
    10. console.log(lastEven); // 10
    11. console.log(reversedIndex); // 1
    12. console.log(lastEvenIndex); // 4

    看着的确麻烦,findLast()findLastIndex()出来后,数组就支持后序查找元素了,实现同样的需求,代码一下子简洁了不少:

    1. const nums = [7, 14, 3, 8, 10, 9];
    2. const lastEven = nums.findLast((num) => num % 2 === 0);
    3. const lastEvenIndex = nums.findLastIndex((num) => num % 2 === 0);
    4. console.log(lastEven); // 10
    5. console.log(lastEvenIndex); // 4
     
    

    你看代码是不是短了很多,并且可读性和正确性都提高了!

  • 相关阅读:
    知识蒸馏和知识图谱相结合的大模型微调方案
    智慧灾备解决方案-最新全套文件
    linux 压缩命令之tar工具的基本使用
    电大搜题:开启智慧学习新时代
    Archive Team: The Twitter Stream Grab
    JAVA计算机毕业设计毕业生论文管理系统Mybatis+源码+数据库+lw文档+系统+调试部署
    C语言练习题——实参形参
    Uboot spi-nor 设备信息定义及3地址模式和4地址模式的理解
    中医自学平台---前端网站
    JAVA高级(一)
  • 原文地址:https://blog.csdn.net/m0_64460287/article/details/127928434