ディクショナリに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
は列挙不可になります。
レビューについては、プロパティフラグと記述子の章を参照してください。