当 hasOwnProperty() 为 false 时遍历继承的对象属性

Iterating through inherited object properties when hasOwnProperty() is false

我一直在测试 JavaScript 的 Object.prototype.hasOwnProperty。据我了解,它旨在从继承的对象属性中剔除直接对象属性。

然而,在我迄今为止测试过的人为示例中(包括 MDN's 自己的示例),当 .hasOwnProperty() returns false,这让我对它的功能有点怀疑。所以,

1) 你能否提供我可以在控制台中 运行 的示例代码,它将在 hasOwnProperty() returns false 时记录继承的属性?

2)在这个问题中添加hasOwnProperty标签时,弹出的SO描述是“...不遍历原型链”。如果是这样的话,Mozilla 下面的例子有什么意义,因为“else 子句将永远不会被执行?

这是 Mozilla 的示例代码:

var buz = {   fog: 'stack' };

for (var name in buz) {   if (buz.hasOwnProperty(name)) {
      console.log('this is fog (' + name + ') for sure. Value: ' + buz[name]);   
  } else {
      console.log(name); // toString or something else
  }
}

for...in 仅迭代可枚举属性。 Object.prototype 上的所有属性都是不可枚举的,因此它们实际上不会被迭代。

这是一个显示继承属性的示例。我们创建一个继承自另一个对象的新对象,而不是继承自 Object.prototype:

var foo = {abc: 123};
// Creates an object with property `fog: 'stack'` but has `foo` as its prototype
var buz = Object.create(foo, {fog: {value: 'stack', enumerable: true}}); 

for (var name in buz) {
  if (Object.prototype.hasOwnProperty.call(buz, name)) {
    console.log('this is fog (' + name + ') for sure. Value: ' + buz[name]);   
  } else {
    console.log(name); // toString or something else
  }
}

(当然我们也可以分配给Object.prototype,但我们正在努力成为好公民:))

在没有 hasOwnProperty() 的情况下使用 for...in 循环将 return 原型链中的可枚举属性。

这是对我的问题第 2 部分的回答。摘自 MDN 站点,但隐藏在 Object.getOwnPropertyNames()

If you want only the enumerable properties, see Object.keys() or use a for...in loop (although note that this will return enumerable properties not found directly upon that object but also along the prototype chain for the object unless the latter is filtered with hasOwnProperty()).

因此,即使在 MDN 示例中创建的对象没有继承的、可枚举的属性,如果满足这些条件,您会看到输出的差异(即更多属性将记录到控制台) , 如果你不雇用 hasOwnProperty().