首页  >  文章  >  web前端  >  现代开发必须了解的 JavaScript ESFeatures

现代开发必须了解的 JavaScript ESFeatures

WBOY
WBOY原创
2024-08-29 10:39:08333浏览

Must-Know JavaScript ESFeatures for Modern Development

JavaScript 不断发展,随着 ES13 (ECMAScript 2022) 的引入,开发人员应该了解一些新功能,以便编写更高效、更现代的代码。在本文中,我们将深入探讨 ES13 中十个最有影响力的功能,这些功能可以改善您的开发工作流程。

1. 顶级等待

ES13 之前:

以前,您只能在异步函数中使用await。这意味着如果您需要使用await,则必须将代码包装在异步函数中,即使模块的其余部分不需要它。

示例:

// Without top-level await (Before ES13)
async function fetchData() {
  const data = await fetch('/api/data');
  return data.json();
}
fetchData().then(console.log);

ES13特点:

使用 ES13,您现在可以在模块的顶层使用 wait,从而无需额外的异步包装函数。

// With top-level await (ES13)
const data = await fetch('/api/data');
console.log(await data.json());

2. 私有实例方法和访问器

ES13 之前:

在 ES13 之前,JavaScript 类没有真正的私有字段或方法。开发人员经常使用下划线或闭包等命名约定来模拟隐私,但这些方法并不是真正的隐私。

示例:

// Simulating private fields (Before ES13)
class Person {
  constructor(name) {
    this._name = name; // Conventionally "private"
  }

  _getName() {
    return this._name;
  }

  greet() {
    return `Hello, ${this._getName()}!`;
  }
}

const john = new Person('John');
console.log(john._getName()); // Accessible, but intended to be private

ES13特点:

ES13 引入了真正的私有实例方法和使用 # 前缀的访问器,确保它们无法在类外部访问。

// Private instance methods and fields (ES13)
class Person {
  #name = '';

  constructor(name) {
    this.#name = name;
  }

  #getName() {
    return this.#name;
  }

  greet() {
    return `Hello, ${this.#getName()}!`;
  }
}

const john = new Person('John');
console.log(john.greet()); // Hello, John!
console.log(john.#getName()); // Error: Private field '#getName' must be declared in an enclosing class

3. 静态类字段和方法

ES13 之前:

在 ES13 之前,静态字段和方法通常在类体之外定义,导致代码内聚力较差。

示例:

// Static fields outside class body (Before ES13)
class MathUtilities {}

MathUtilities.PI = 3.14159;

MathUtilities.calculateCircumference = function(radius) {
  return 2 * MathUtilities.PI * radius;
};

console.log(MathUtilities.PI); // 3.14159
console.log(MathUtilities.calculateCircumference(5)); // 31.4159

ES13特点:

ES13 允许您直接在类体内定义静态字段和方法,从而提高可读性和组织性。

// Static fields and methods inside class body (ES13)
class MathUtilities {
  static PI = 3.14159;

  static calculateCircumference(radius) {
    return 2 * MathUtilities.PI * radius;
  }
}

console.log(MathUtilities.PI); // 3.14159
console.log(MathUtilities.calculateCircumference(5)); // 31.4159

4. 逻辑赋值运算符

ES13 之前:

逻辑运算符(&&、||、??)和赋值通常在详细语句中手动组合,导致代码更加复杂。

示例:

// Manually combining logical operators and assignment (Before ES13)
let a = 1;
let b = 0;

a = a && 2;  // a = 2
b = b || 3;  // b = 3
let c = null;
c = c ?? 4; // c = 4

console.log(a, b, c); // 2, 3, 4

ES13特点:

ES13 引入了逻辑赋值运算符,它以简洁的语法将逻辑运算与赋值结合起来。

// Logical assignment operators (ES13)
let a = 1;
let b = 0;

a &&= 2;  // a = a && 2; // a = 2
b ||= 3;  // b = b || 3; // b = 3
let c = null;
c ??= 4; // c = c ?? 4; // c = 4

console.log(a, b, c); // 2, 3, 4

5. WeakRefs 和 FinalizationRegistry

ES13 之前:

JavaScript 本身不支持弱引用和终结器,这使得在某些情况下管理资源变得困难,尤其是处理昂贵对象的大型应用程序。

示例:

// No native support for weak references (Before ES13)
// Developers often had to rely on complex workarounds or external libraries.

ES13特点:

ES13引入了WeakRef和FinalizationRegistry,为弱引用和垃圾回收后的清理任务提供原生支持。

// WeakRefs and FinalizationRegistry (ES13)
let obj = { name: 'John' };
const weakRef = new WeakRef(obj);

console.log(weakRef.deref()?.name); // 'John'

obj = null; // obj is eligible for garbage collection

setTimeout(() => {
  console.log(weakRef.deref()?.name); // undefined (if garbage collected)
}, 1000);

const registry = new FinalizationRegistry((heldValue) => {
  console.log(`Cleanup: ${heldValue}`);
});

registry.register(obj, 'Object finalized');

6. 私人领域的人体工学品牌检查

ES13 之前:

检查对象是否具有私有字段并不简单,因为私有字段本身并不支持。开发人员必须依赖解决方法,例如检查公共属性或使用 instanceof 检查。

示例:

// Checking for private fields using workarounds (Before ES13)
class Car {
  constructor() {
    this.engineStarted = false; // Public field
  }

  startEngine() {
    this.engineStarted = true;
  }

  static isCar(obj) {
    return obj instanceof Car; // Not reliable for truly private fields
  }
}

const myCar = new Car();
console.log(Car.isCar(myCar)); // true

ES13特点:

使用 ES13,您现在可以使用 # 语法直接检查对象是否具有私有字段,使其更简单、更可靠。

// Ergonomic brand checks for private fields (ES13)
class Car {
  #engineStarted = false;

  startEngine() {
    this.#engineStarted = true;
  }

  static isCar(obj) {
    return #engineStarted in obj;
  }
}

const myCar = new Car();
console.log(Car.isCar(myCar)); // true

7. Array.prototype.at()

ES13 之前:

使用带索引的括号表示法访问数组中的元素,对于负索引,您必须手动计算位置。

示例:

// Accessing array elements (Before ES13)
const arr = [1, 2, 3, 4, 5];
console.log(arr[arr.length - 1]); // 5 (last element)

ES13特点:

at() 方法允许您更直观地使用正索引和负索引访问数组元素。

// Accessing array elements with `at()` (ES13)
const arr = [1, 2, 3, 4, 5];
console.log(arr.at(-1)); // 5 (last element)
console.log(arr.at(0)); // 1 (first element)

8. Object.hasOwn()

ES13 之前:

要检查对象是否有自己的属性(不是继承的),开发人员通常使用 Object.prototype.hasOwnProperty.call() 或 obj.hasOwnProperty()。

示例:

// Checking own properties (Before ES13)
const obj = { a: 1 };
console.log(Object.prototype.hasOwnProperty.call(obj, 'a')); // true
console.log(obj.hasOwnProperty('a')); // true

ES13特点:

新的 Object.hasOwn() 方法简化了此检查,提供了更简洁和可读的语法。

// Checking own properties with `Object.hasOwn()` (ES13)
const obj = { a: 1 };
console.log(Object.hasOwn(obj, 'a')); // true

9. Object.fromEntries()

ES13 之前:

将键值对(例如,从 Map 或数组)转换为对象需要循环和手动构造。

Example:

// Creating an object from entries (Before ES13)
const entries = [['name', 'John'], ['age', 30]];
const obj = {};
entries.forEach(([key, value]) => {
  obj[key] = value;
});
console.log(obj); // { name: 'John', age: 30 }

ES13 Feature:

Object.fromEntries() simplifies the creation of objects from key-value pairs.

// Creating an object with `Object.fromEntries()` (ES13)
const entries = [['name', 'John'], ['age', 30]];
const obj = Object.fromEntries(entries);
console.log(obj); // { name: 'John', age: 30 }

10. Global This in Modules

Before ES13:

The value of this in the top level of a module was undefined, leading to confusion when porting code from scripts to modules.

Example:

// Global `this` (Before ES13)
console.log(this); // undefined in modules, global object in scripts

ES13 Feature:

ES13 clarifies that the value of this at the top level of a module is always undefined, providing consistency between modules and scripts.

// Global `this` in modules (ES13)
console.log(this); // undefined

These ES13 features are designed to make your JavaScript code more efficient, readable, and maintainable. By integrating these into your development practices, you can leverage the latest advancements in the language to build modern, performant applications.

以上是现代开发必须了解的 JavaScript ESFeatures的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn