共同点:可以用来遍历对象

输入
for…in 输出自身以及原型链上可枚举的属性 key2、key1
Object.keys 获取对象自身可枚举的属性键
等价于for in+hasOwnProperty的效果
b
Object.getOwnPropertyNames 获取对象自身的全部属性名 b c

目标:遍历child中的属性

  1. var parent = Object.create(Object.prototype, {
  2. key1: {
  3. value: 1,
  4. writable: true,
  5. enumerable: true,
  6. configurable: true
  7. }
  8. });
  9. var child = Object.create(parent, {
  10. key2: {
  11. value: 2,
  12. writable: true,
  13. enumerable: true,
  14. configurable: true
  15. },
  16. key3: {
  17. value: 3,
  18. writable: true,
  19. enumerable: false,
  20. configurable: true
  21. }
  22. });

for…in

  1. for (let k in child) {
  2. console.log(k);
  3. }
  4. // key2
  5. // key1

for…in + hasOwnProperty

  1. for (let k in child) {
  2. if (child.hasOwnProperty(k)) {
  3. console.log(k);
  4. }
  5. }
  6. // key2

Object.keys

  1. Object.keys(child);
  2. // ['key2']

Object.getOwnPropertyNames

  1. Object.getOwnPropertyNames(child);
  2. // (2) ['key2', 'key3']