Vue源码中Object.create(null)的使用

216 阅读1分钟

Vue源码中Object.create(null)的使用

在vue源码中看到很多 Object.create(null) 这种写法,比如:

// keep-alive.js中
  created () {
    this.cache = Object.create(null) // 创建一个对象,该对象不继承任何东西,原型也是null
    this.keys = []
  },
​
  destroyed () {
    for (const key in this.cache) { // 好处就是这里 for in 遍历时,不用再使用hasOwnProperty来排除了
      pruneCacheEntry(this.cache, key, this.keys)
    }
  },

好处就是: for in 遍历时,不用再使用hasOwnProperty来排除继承来的属性了

参考 Creating object with Object.create(null)

It would be convenient to create an object that does not inherit from a prototype at all in case you want to use object as hash/map arbitrary keys to values.