ホームページ  >  記事  >  ウェブフロントエンド  >  最新の開発のために知っておくべき JavaScript ES の機能

最新の開発のために知っておくべき JavaScript ES の機能

WBOY
WBOYオリジナル
2024-08-29 10:39:08245ブラウズ

Must-Know JavaScript ESFeatures for Modern Development

JavaScript は進化し続けており、ES13 (ECMAScript 2022) の導入により、開発者がより効率的で最新のコードを作成するために知っておくべき新機能がいくつかあります。この記事では、開発ワークフローを改善できる ES13 の最も影響力のある 10 個の機能について詳しく説明します。

1. トップレベルの待機

ES13 より前:

以前は、async 関数内でのみ await を使用できました。つまり、await を使用する必要がある場合は、モジュールの残りの部分で await が必要ない場合でも、コードを async 関数内にラップする必要があります。

例:

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

ES13 の機能:

ES13 では、モジュールのトップレベルで await を使用できるようになり、追加の非同期ラッパー関数が必要なくなりました。

// 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. WeakRef と 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 より前:

キーと値のペア (マップや配列など) をオブジェクトに変換するには、ループと手動の構築が必要です。

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 ES の機能の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。