Object.create(null) 和 {} 有什么区别?什么时候用 Object.create(null)?

核心区别

const obj1 = {}
const obj2 = Object.create(null)

obj1.__proto__            // Object.prototype
obj2.__proto__            // undefined
Object.getPrototypeOf(obj2)  // null

使用场景

  1. 字典/Map:避免原型链上的属性干扰
// 问题:原型属性干扰
const dict = {}
dict.constructor  // ƒ Object() {...](原型链上的属性)

// 解决:纯净对象
const pureDict = Object.create(null)
pureDict.constructor  // undefined
pureDict.hasOwnProperty  // undefined
  1. 防止原型污染
// 作为缓存对象时,避免 __proto__ 等特殊属性名冲突
const cache = Object.create(null)
cache['__proto__'] = 'value'  // 安全,不会污染原型链
  1. Vue 源码中的使用:Vue 内部大量使用 Object.create(null) 创建无原型的对象作为缓存映射表,性能更好。

注意事项

const obj = Object.create(null)
obj + ''           // TypeError: Cannot convert object to primitive value
`${obj}`          // TypeError
JSON.stringify(obj) // '{}'  ✅ 正常

同分类其他题目