Object.defineProperty 中 enumerable 的意思

806 阅读1分钟

enumerable

含义:表示对象属性是否可枚举。

下面举例来看看创建对象的时候 enumerable 的情况

例子
const cat = {};
Object.defineProperty(cat, "price", {
  value: 100,
  enumerable: false, // 默认为 false
});
Object.defineProperty(cat, "name", {
  value: "jojo",
  enumerable: true, // 说明在 for in 中是可以遍历得到
});
console.log("price" in cat); // true
console.log(cat.hasOwnProperty("price")); // true
for (const key in cat) {
  console.log(key); // name
}
Object.keys(cat); // name

直接声明的对象属性默认是可枚举的

const cat = { x: 1, y: 2 };
for (const key in cat) {
  console.log(key); // x , y
}
Object.keys(cat); // x, y

用Object.create()出来的对象,然后复制属性也是可枚举的

const cat = { x: 1, y: 2 };
const obj = Object.create(cat);
obj.z = 3;
for (const key in obj) {
  console.log(key); // x, y, z
}
Object.keys(obj); // x, y, z

结论

最后用 for in 遍历或者 Object.keys 取对象的属性只会遍历出 enumerable:true 的属性。