Object.prototype.hasOwnProperty()

Object 实例的 hasOwnProperty() 方法返回一个布尔值,指示该对象是否将指定属性作为其自己的属性(而不是继承它)。

¥The hasOwnProperty() method of Object instances returns a boolean indicating whether this object has the specified property as its own property (as opposed to inheriting it).

注意:在支持 Object.hasOwn() 的浏览器中,建议使用 Object.hasOwn(),而不是 hasOwnProperty()

¥Note: Object.hasOwn() is recommended over hasOwnProperty(), in browsers where it is supported.

Try it

语法

¥Syntax

js
hasOwnProperty(prop)

参数

¥Parameters

prop

要测试的属性的 String 名称或 符合

返回值

¥Return value

如果对象具有指定属性作为自己的属性,则返回 true;否则为 false

¥Returns true if the object has the specified property as own property; false otherwise.

描述

¥Description

如果指定的属性是对象的直接属性,则 hasOwnProperty() 方法将返回 true — 即使该值为 nullundefined。如果属性是继承的,或者根本没有声明,则该方法返回 false。与 in 运算符不同,此方法不会检查对象原型链中的指定属性。

¥The hasOwnProperty() method returns true if the specified property is a direct property of the object — even if the value is null or undefined. The method returns false if the property is inherited, or has not been declared at all. Unlike the in operator, this method does not check for the specified property in the object's prototype chain.

该方法可以在大多数 JavaScript 对象上调用,因为大多数对象都是从 Object 派生的,因此继承了它的方法。例如 ArrayObject,因此可以使用 hasOwnProperty() 方法来检查索引是否存在:

¥The method can be called on most JavaScript objects, because most objects descend from Object, and hence inherit its methods. For example Array is an Object, so you can use hasOwnProperty() method to check whether an index exists:

js
const fruits = ["Apple", "Banana", "Watermelon", "Orange"];
fruits.hasOwnProperty(3); // true ('Orange')
fruits.hasOwnProperty(4); // false - not defined

该方法在重新实现的对象或 null-原型对象 上不可用(因为它们不是从 Object.prototype 继承的)。下面给出了这些情况的示例。

¥The method will not be available in objects where it is reimplemented, or on null-prototype objects (as these don't inherit from Object.prototype). Examples for these cases are given below.

示例

¥Examples

使用 hasOwnProperty 测试自有属性是否存在

¥Using hasOwnProperty to test for an own property's existence

以下代码演示如何确定 example 对象是否包含名为 prop 的属性。

¥The following code shows how to determine whether the example object contains a property named prop.

js
const example = {};
example.hasOwnProperty("prop"); // false

example.prop = "exists";
example.hasOwnProperty("prop"); // true - 'prop' has been defined

example.prop = null;
example.hasOwnProperty("prop"); // true - own property exists with value of null

example.prop = undefined;
example.hasOwnProperty("prop"); // true - own property exists with value of undefined

直接属性与继承属性

¥Direct vs. inherited properties

以下示例区分直接属性和通过原型链继承的属性:

¥The following example differentiates between direct properties and properties inherited through the prototype chain:

js
const example = {};
example.prop = "exists";

// `hasOwnProperty` will only return true for direct properties:
example.hasOwnProperty("prop"); // true
example.hasOwnProperty("toString"); // false
example.hasOwnProperty("hasOwnProperty"); // false

// The `in` operator will return true for direct or inherited properties:
"prop" in example; // true
"toString" in example; // true
"hasOwnProperty" in example; // true

迭代对象的属性

¥Iterating over the properties of an object

以下示例演示如何迭代对象的可枚举属性而不执行继承的属性。

¥The following example shows how to iterate over the enumerable properties of an object without executing on inherited properties.

js
const buz = {
  fog: "stack",
};

for (const name in buz) {
  if (buz.hasOwnProperty(name)) {
    console.log(`this is fog (${name}) for sure. Value: ${buz[name]}`);
  } else {
    console.log(name); // toString or something else
  }
}

请注意,for...in 循环仅迭代可枚举项:循环中没有发出不可枚举属性并不意味着 hasOwnProperty 本身严格限于可枚举项。你可以使用 Object.getOwnPropertyNames() 迭代不可枚举的属性。

¥Note that the for...in loop only iterates enumerable items: the absence of non-enumerable properties emitted from the loop does not imply that hasOwnProperty itself is confined strictly to enumerable items. You can iterate over non-enumerable properties with Object.getOwnPropertyNames().

使用 hasOwnProperty 作为属性名称

¥Using hasOwnProperty as a property name

JavaScript 不保护属性名称 hasOwnProperty;具有此名称属性的对象可能会返回不正确的结果:

¥JavaScript does not protect the property name hasOwnProperty; an object that has a property with this name may return incorrect results:

js
const foo = {
  hasOwnProperty() {
    return false;
  },
  bar: "Here be dragons",
};

foo.hasOwnProperty("bar"); // re-implementation always returns false

解决此问题的推荐方法是使用 Object.hasOwn()(在支持它的浏览器中)。其他替代方案包括使用外部 hasOwnProperty

¥The recommended way to overcome this problem is to instead use Object.hasOwn() (in browsers that support it). Other alternatives include using an external hasOwnProperty:

js
const foo = { bar: "Here be dragons" };

// Use Object.hasOwn() method - recommended
Object.hasOwn(foo, "bar"); // true

// Use the hasOwnProperty property from the Object prototype
Object.prototype.hasOwnProperty.call(foo, "bar"); // true

// Use another Object's hasOwnProperty
// and call it with 'this' set to foo
({}).hasOwnProperty.call(foo, "bar"); // true

请注意,在前两种情况下,没有新创建的对象。

¥Note that in the first two cases there are no newly created objects.

使用 Object.create(null) 创建的对象

¥Objects created with Object.create(null)

null-原型对象 不继承自 Object.prototype,导致 hasOwnProperty() 无法访问。

¥null-prototype objects do not inherit from Object.prototype, making hasOwnProperty() inaccessible.

js
const foo = Object.create(null);
foo.prop = "exists";
foo.hasOwnProperty("prop"); // Uncaught TypeError: foo.hasOwnProperty is not a function

这种情况的解决方案与上一节相同:优先使用 Object.hasOwn(),否则使用外部对象的 hasOwnProperty()

¥The solutions in this case are the same as for the previous section: use Object.hasOwn() by preference, otherwise use an external object's hasOwnProperty().

规范

Specification
ECMAScript Language Specification
# sec-object.prototype.hasownproperty

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看