测试 Object.hasOwnProperty

Testing Object.hasOwnProperty

我有一个迭代 object 属性的代码实现。

for (const prop in obj) {
    propsMap[prop] = prop;
}

但如前所述,我的 IDE (WebStorm) 建议我使用 obj.hasOwnProperty(prop) 添加 属性 检查以避免迭代不存在的属性:

for (const prop in obj) {
    if (obj.hasOwnProperty(prop)) {
        propsMap[prop] = prop;
    }
}

问题是当前的测试总是 obj.hasOwnProperty(prop)true 并且覆盖率不是我能得到的最好的,我不知道如果 [=17= 会发生什么] 实际上没有 属性 prop.

要对此进行测试,您可以创建从其原型继承某些内容的对象

const obj = Object.create({name: 'inherited'})

name 会伪造 obj.hasOwnProperty('name') 检查。

但是复制对象有更好的选择。例如Object.assign

Object.assign(propsMap, obj)

您还应该记住 obj.hasOwnProperty 检查很容易出错。例如

const obj = {hasOwnProperty: null} // hasOwnProperty is not a function
const obj = Object.create(null) // obj wont inherit hasOwnProperty 

所以至少用

替换它
const hasOwnProperty = {}.hasOwnProperty

for(const name in obj) {
  if(hasOwnProperty.call(obj, name)) {

  }

这对我有用:

const parentObj = {
   defaultProp: 'test'
}

const object = Object.create(parentObj, {
    prop: {
       value: 'test',
       enumerable: true
    }
}

defaultProp 属性 应该 return false 在 hasOwnProperty 检查