JavaScript 系列 - Object.prototype.propertyIsEnumerable

146 阅读1分钟

propertyIsEnumerable(prop)  方法返回一个布尔值,表示指定的属性是否是对象的可枚举自有属性。

用户自定义对象和内置对象

大多数内置属性默认情况下是不可枚举的,而用户创建的对象属性通常是可枚举的,除非明确指定为不可枚举。

const a = ["是可枚举的"];

a.propertyIsEnumerable(0); // true
a.propertyIsEnumerable("length"); // false

Math.propertyIsEnumerable("random"); // false
globalThis.propertyIsEnumerable("Math"); // false

自有属性和继承属性

const o1 = {
  enumerableInherited: "是可枚举的",
};
Object.defineProperty(o1, "nonEnumerableInherited", {
  value: "是不可枚举的",
  enumerable: false,
});
const o2 = {
  // o1 是 o2 的原型
  __proto__: o1,
  enumerableOwn: "是可枚举的",
};
Object.defineProperty(o2, "nonEnumerableOwn", {
  value: "是不可枚举的",
  enumerable: false,
});

o2.propertyIsEnumerable("enumerableInherited"); // false
o2.propertyIsEnumerable("nonEnumerableInherited"); // false
o2.propertyIsEnumerable("enumerableOwn"); // true
o2.propertyIsEnumerable("nonEnumerableOwn"); // false

Symbol 属性

const sym = Symbol("可枚举的");
const sym2 = Symbol("不可枚举的");
const o = {
  [sym]: "是可枚举的",
};
Object.defineProperty(o, sym2, {
  value: "是不可枚举的",
  enumerable: false,
});

o.propertyIsEnumerable(sym); // true
o.propertyIsEnumerable(sym2); // false

在 null 原型对象上使用

const o = {
  __proto__: null,
  enumerableOwn: "是可枚举的",
};

o.propertyIsEnumerable("enumerableOwn"); // TypeError: o.propertyIsEnumerable is not a function
Object.prototype.propertyIsEnumerable.call(o, "enumerableOwn"); // true
const o = {
  __proto__: null,
  enumerableOwn: "是可枚举的",
};

Object.getOwnPropertyDescriptor(o, "enumerableOwn")?.enumerable; // true
Object.getOwnPropertyDescriptor(o, "nonExistent")?.enumerable; // undefined