返回

为什么创建空对象要使用Object.create(null)

当你想用javascript对象作为一个hash映射(完全用来储存数据),你应该按如下方式来创建它。

当创建一个映射使用对象字面量时(const map = {}),默认情况下,这个映射从这个对象继承属性。这和 Object.creatd(Object.prototype)创建时相等的。 但是通过 Object.create(null),我们明确指定 null 作为它的属性。因此它相当于没有属相,甚至没有constructor, toString, hasOwnProperty等方法。因此你可以随意使用这些键值在你的数据结构中,只要你需要。

// vue.js

const dirtyMap = {};
const cleanMap = Object.create(null);

dirtyMap.constructor    // function Object() { [native code] }

cleanMap.constructor    // undefined
cleanMap.__proto__ // undefined
// Iterating maps

const key;
for(key in dirtyMap){
  if (dirtyMap.hasOwnProperty(key)) {   // Check to avoid iterating over inherited properties.
    console.log(key + " -> " + dirtyMap[key]);
  }
}

for(key in cleanMap){
  console.log(key + " -> " + cleanMap[key]);    // No need to add extra checks, as the object will always be clean
}