在字典中添加 toString 方法
重要性:5
有一个名为 dictionary 的对象,它使用 Object.create(null) 创建,用于存储任何 key/value 对。
在其中添加方法 dictionary.toString(),该方法应该返回一个逗号分隔的键列表。您的 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 获取所有可枚举的键,并输出它们的列表。
为了使 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 是不可枚举的。
请参阅属性标志和描述符章节以供复习。