レッスンに戻る

ディクショナリにtoStringを追加する

重要度: 5

「キー/値」のペアを格納するためにObject.create(null)として作成されたディクショナリオブジェクトがあります。

メソッドdictionary.toString()を組み込みます。これは、キーのコンマ区切りリストを返します。オブジェクトでfor..inを使用してtoStringが表示されるまではなりません。

次の方法で動作します。

let dictionary = Object.create(null);

// your code to add dictionary.toString method

// add some data
dictionary.apple = "Apple";
dictionary.__proto__ = "test"; // __proto__ is a regular property key here

// only apple and __proto__ are in the loop
for(let key in dictionary) {
  alert(key); // "apple", then "__proto__"
}

// your toString in action
alert(dictionary); // "apple,__proto__"

このメソッドは、Object.keysを使用して列挙可能なすべてのキーを取得し、そのリストを出力できます。

toStringを列挙不可にするには、プロパティ記述子を使用して定義します。Object.createの構文では、プロパティ記述子が2番目の引数として指定されたオブジェクトを提供できます。

let dictionary = Object.create(null, {
  toString: { // define toString property
    value() { // the value is a function
      return Object.keys(this).join();
    }
  }
});

dictionary.apple = "Apple";
dictionary.__proto__ = "test";

// apple and __proto__ is in the loop
for(let key in dictionary) {
  alert(key); // "apple", then "__proto__"
}

// comma-separated list of properties by toString
alert(dictionary); // "apple,__proto__"

記述子を使用してプロパティを作成すると、フラグはデフォルトでfalseになります。したがって、上記のコードではdictionary.toStringは列挙不可になります。

レビューについては、プロパティフラグと記述子の章を参照してください。