Object.prototype.hasOwnProperty() 语法
hasOwnProperty() 是 JavaScript Object 对象实例中一个方法,它用于判断一个对象是否拥有指定的自身属性(即非继承属性)。
语法:
obj.hasOwnProperty(prop)说明:
hasOwnProperty() 方法接收单个参数。
prop(必选):要检测的属性的名称,是一个字符串或 Symbol。
对于 hasOwnProperty() 方法,小伙伴们需要清楚以下几点。
- 只检查自身属性:hasOwnProperty() 方法不会沿着原型链查找继承的属性。这是它与 in 运算符的主要区别。
- 能处理 Symbol 属性:hasOwnProperty() 能够正确检测 Symbol 类型的属性键。
- 存在安全性问题:如果一个对象本身覆盖了 hasOwnProperty() 方法(比如对象有一个名为 hasOwnProperty 的属性,或者原型链上的某个对象重写了它),直接调用 obj.hasOwnProperty() 可能会导致意外或不正确的行为。为了避免这种情况,强烈建议使用 Object.hasOwn(obj, prop) 来代替它。
提示: Object.prototype.hasOwnProperty() 是 Object 原型链上的方法。也就是说,所有继承自 Object.prototype 的对象都默认拥有这个方法,并且可以通过对象实例直接调用(如 myObject.hasOwnProperty("propertyName"))。
Object.prototype.hasOwnProperty() 摘要
| 属于 | JavaScript Object 对象 |
|---|---|
| 使用频率 | 中 |
| 官方文档 | 查看 |
| MDN | 查看 |
Object.prototype.hasOwnProperty() 示例
接下来,我们通过几个简单的例子来讲解一下 hasOwnProperty() 方法是如何使用的。
示例 1:hasOwnProperty() 检查自身属性
const user = {
name: "Jack",
age: 20
};
console.log(user.hasOwnProperty("name"));
console.log(user.hasOwnProperty("email"));运行结果如下。
true
false分析:
需要注意的是,hasOwnProperty() 的参数是一个字符串。
// 正确
user.hasOwnProperty("name")
// 错误
user.hasOwnProperty(name)示例 2:hasOwnProperty() 区分自身属性和继承属性
function ParentBox() {
this.color = "red";
}
function ChildBox() {
this.width = 20;
this.height = 40;
}
ChildBox.prototype = new ParentBox();
const box = new ChildBox();
// 判断继承属性
const result1 = box.hasOwnProperty("color");
console.log(result1);
// 判断自身属性
const result2 = box.hasOwnProperty("width");
console.log(result2);运行结果如下。
false
true分析:
我们都知道,in 运算符会检查整个原型链。而对于 hasOwnProperty() 来说,它只会关注对象自身的属性。
color 是继承过来的属性,因此 box.hasOwnProperty("color") 返回 false。而 width 是自身的属性,因此 box.hasOwnProperty("width") 返回 true。
示例 3:hasOwnProperty() 可以判断 Symbol 键的自身属性
const uniqueId = Symbol("userId");
const statusKey = Symbol("status");
const userData = {
name: "Jack",
[uniqueId]: "UID-007"
};
console.log(userData.hasOwnProperty("name"));
console.log(userData.hasOwnProperty(uniqueId));
console.log(userData.hasOwnProperty(statusKey));运行结果如下。
true
true
false分析:
hasOwnProperty() 方法能够正确地检测 Symbol 类型的属性键。
