Javascript 测试对象.hasOwnProperty

Javascript 测试对象.hasOwnProperty,javascript,jasmine,code-coverage,Javascript,Jasmine,Code Coverage,我有一个迭代对象属性的代码实现 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; } } 问题是当

我有一个迭代
对象
属性的代码实现

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)
真的
,覆盖范围不是我能得到的最好的,我不知道如果
obj
实际上没有属性
prop
,要测试这一点,你可以创建从原型继承某些东西的对象

const obj = Object.create({name: 'inherited'})
name
将失效
obj.hasOwnProperty('name')
检查

但复制对象有更好的选择。比如说

您还应该记住,
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)) {

  }

“如果obj实际上没有财产属性,会发生什么情况”。该对象可能通过prototype从另一个对象继承。在这种情况下,这些属性将被迭代,但不是“自己的”。如果您没有从其他对象继承,只是使用
var obj={…}
创建您的对象,那么
hasOwnProperty
检查是无用的。该对象可以来自任何地方,因为它位于我正在创建的库中(最初是typescript,但这不是typescript相关问题,所以我没有将其标记为typescript)。我认为测试在这里并没有什么用处,但我想知道如何创建一个对象,以便
obj.hasOwnProperty(prop)
false
。那么
object.keys(obj.forEach(prop=>{propsMap[prop]=prop})
呢?获取覆盖范围要容易得多我不能使用Object.assign,因为propsMap是一个类型脚本映射,所以我使用hasOwnProperty。编辑:我没有时间检查原因,但是Object.keys(obj).forEach(…)没有通过我当前的测试,而Object.keys(obj).forEach(…)没有通过。@Supamiu您也可以这样构造它
const-propsMap=new-Map(Object.entries(obj))
这是当前的propsMap(typescript):
const-propsMap:{[index:string]}={}@Supamiu至少编译:)
const hasOwnProperty = {}.hasOwnProperty

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

  }