Object.create(null) 和 {} 有什么区别?什么时候用 Object.create(null)?
核心区别
const obj1 = {}
const obj2 = Object.create(null)
obj1.__proto__
obj2.__proto__
Object.getPrototypeOf(obj2)
{}:原型指向 Object.prototype,继承了 toString、hasOwnProperty 等方法
Object.create(null):原型为 null,是一个纯净对象,没有任何原型方法
使用场景
- 字典/Map:避免原型链上的属性干扰
const dict = {}
dict.constructor
const pureDict = Object.create(null)
pureDict.constructor
pureDict.hasOwnProperty
- 防止原型污染
const cache = Object.create(null)
cache['__proto__'] = 'value'
- Vue 源码中的使用:Vue 内部大量使用
Object.create(null) 创建无原型的对象作为缓存映射表,性能更好。
注意事项
Object.create(null) 创建的对象没有 toString,某些操作会出错:
const obj = Object.create(null)
obj + ''
`${obj}`
JSON.stringify(obj)
同分类其他题目