Object.prototype.propertyIsEnumerable() 语法
propertyIsEnumerable() 是 JavaScript Object 对象实例的一个方法,它用于判断对象自身的某个属性是否为可枚举的。所谓的可枚举属性,指的是那些可以被 for...in 循环或 Object.keys() 遍历到的属性。
语法:
obj.propertyIsEnumerable(prop)说明:
propertyIsEnumerable() 方法接收单个参数。
prop(必选):要判断的属性的名称,是一个字符串或 Symbol。
对于 propertyIsEnumerable() 方法,小伙伴们要清楚以下几点。
- 只检查自身属性:propertyIsEnumerable() 不会沿着原型链查找继承的属性。这是它与 for...in 循环的一个关键区别,for...in 会遍历原型链上的可枚举属性。
- 同时检查自身和可枚举性:如果属性不存在,或属性是继承的,或属性存在但不可枚举,propertyIsEnumerable() 都会返回 false。
- 可以处理 Symbol 属性:propertyIsEnumerable() 能够正确检测 Symbol 类型的属性键是否是可枚举的。
Object.prototype.propertyIsEnumerable() 摘要
| 属于 | JavaScript Object 对象 |
|---|---|
| 使用频率 | 低 |
| 官方文档 | 查看 |
| MDN | 查看 |
Object.prototype.propertyIsEnumerable() 示例
接下来,我们通过几个简单的例子来讲解一下 propertyIsEnumerable() 方法是如何使用的。
示例 1:propertyIsEnumerable() 基本用法
const user = {
name: "阿莫",
age: 20,
city: "广州"
};
console.log(user.propertyIsEnumerable("name"));
console.log(user.propertyIsEnumerable("age"));
console.log(user.propertyIsEnumerable("country"));运行结果如下。
true
true
false分析:
对于普通对象字面量中定义的属性,propertyIsEnumerable() 会直接返回 true,因为这些属性通常是可枚举的。而对于不存在的属性,propertyIsEnumerable() 则会返回 false。
示例 2:propertyIsEnumerable() 区分自身可枚举属性和不可枚举属性
const appConfig = {
appName: "Lvyenet",
version: "1.0.0"
};
// 添加一个不可枚举的自身属性
Object.defineProperty(appConfig, "secretKey", {
value: "abc-123-xyz",
enumerable: false, // 设置为不可枚举
writable: false,
configurable: false
});
console.log(appConfig.propertyIsEnumerable("appName")); // true
console.log(appConfig.propertyIsEnumerable("secretKey")); // false
// 使用 Object.keys() 验证
console.log(Object.keys(appConfig));
// 使用 for...in 循环验证
for (const key in appConfig) {
console.log(key);
}运行结果如下。
true
false
[ 'appName', 'version' ]
appName
version分析:
for...in 循环和 Object.keys() 这两个,都只会处理对象的可枚举属性。
示例 3:propertyIsEnumerable() 区分自身属性和继承属性
function ParentBox() {
this.color = "red";
}
function ChildBox() {
this.width = 20;
this.height = 40;
}
ChildBox.prototype = new ParentBox();
const box = new ChildBox();
// 判断继承属性
const result1 = box.propertyIsEnumerable("color");
console.log(result1);
// 判断自身属性
const result2 = box.propertyIsEnumerable("width");
console.log(result2);运行结果如下。
false
true分析:
propertyIsEnumerable() 不仅要求属性存在,还要求属性是自身属性且可枚举的。对于继承属性来说,即使它们在原型上是可枚举的,propertyIsEnumerable() 也会返回 false
示例 4:propertyIsEnumerable() 处理 Symbol 属性
const privateData = Symbol("data");
const publicId = Symbol("id");
const record = {
value: 100,
[publicId]: "RECORD-ABC"
};
Object.defineProperty(record, privateData, {
value: "secret",
enumerable: false // 设置为不可枚举
});
console.log(record.propertyIsEnumerable("value")); // true
console.log(record.propertyIsEnumerable(publicId)); // true
console.log(record.propertyIsEnumerable(privateData)); // false运行结果如下。
true
true
false分析:
propertyIsEnumerable() 对于 Symbol 类型的属性键同样有效,能够判断它们是否是可枚举的自身属性。
