將 toString 加入字典
重要性:5
有一個物件 dictionary
,建立為 Object.create(null)
,用來儲存任何 key/value
成對資料。
加入方法 dictionary.toString()
,它應該回傳一個以逗號分隔的 key 清單。你的 toString
不應該出現在物件的 for..in
中。
以下是它的運作方式
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
取得所有可列舉的 key,並輸出它們的清單。
為了讓 toString
不可列舉,我們使用屬性描述符來定義它。Object.create
的語法允許我們提供一個物件作為第二個參數,其中包含屬性描述符。
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
是不可列舉的。
請參閱章節 屬性旗標和描述符 以複習。