拡張オブジェクトリテラル

PHPz
リリース: 2024-08-24 11:03:18
オリジナル
200 人が閲覧しました

Enhanced Object Literals

  • ES6 introduced 3 ways to write object literals
  • First Way:
- ES6 Enhanced object literal syntax can take an external object like salary object and make it a property of the developer object as shown below:
const salary = {
  fixed: '$200k',
  variable: '$100k'
}

const developer = {
  // salary: salary      // Before ES6
  salary                 // ES6 way
}

developer; // { salary: { fixed: '$200k', variable: '$100k' } }

- If any change is made in salary object, same change needs to be made inside the developer object for salary object which is present as property of developer object.
ログイン後にコピー
  • Second way:
  • We don't need to create a property & then set it to function expression. We can write that directly without function keyword as shown below i.e ES6 Way.
const salary = {
  fixed: '$200k',
  variable: '$50k'
}

const developer = {
  salary,
  /* Before ES6
  greet: function(name){
    console.log(`Salary credited. Enjoy ${name}!`);
  }*/
  // ES6 Way
  greet(name){
    console.log(`Salary credited. Enjoy ${name}!`);
  }
}

developer.greet("Peter");
ログイン後にコピー
  • Third Way:
  • Property names can be computed also
const seasons = ['winter','summer','spring', 'monsoon','autumn'];

const fruits = {
  [seasons[0]]: 'apple',
  [seasons[1]]: 'mango',
  [[seasons.length]]: 'cherry'
}

fruits;   // { '5': 'cherry', winter: 'apple', summer: 'mango' }
ログイン後にコピー

以上が拡張オブジェクトリテラルの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!