Object.prototype.hasOwnProperty() - JavaScript 编辑

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

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

Syntax

obj.hasOwnProperty(prop)

Parameters

prop
The String name or Symbol of the property to test.

Return value

A Boolean indicating whether or not the object has the specified property as own property.

Description

All descendents of Object inherit the hasOwnProperty method. This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check for a property in the object's prototype chain. If an Object is an Array, hasOwnProperty method can check whether an index exists.

Polyfill

;(function(hasOwnProp) { // IIFE with guarding semicolon
  function hasOwnProperty(name) {
    if (this == null) { throw new TypeError("Cannot convert undefined or null to object!") }
    var O = Object(this), key = String(name);
    var _proto = O.__proto__ || O.constructor.prototype || {}; // Object.prototype
    return key in O && ( !(key in _proto) || O[key] !== _proto[key] );
  }
  if (!hasOwnProp) {
    try {
      Object.defineProperty( Object.prototype, 'hasOwnProperty', {
        enumerable: false, configurable: true, writable: true,
        value: hasOwnProperty
      });
    } catch (e) { // Object.defineProperty isn't supported
      Object.prototype['hasOwnProperty'] = hasOwnProperty;
    }
  }
})(Object.prototype.hasOwnProperty);

Note

hasOwnProperty returns true even if the value of the property is null or undefined.

o = new Object();
o.propOne = null;
o.hasOwnProperty('propOne');   // returns true
o.propTwo = undefined;
o.hasOwnProperty('propTwo');   // returns true

Examples

Using hasOwnProperty to test for a property's existence

The following example determines whether the o object contains a property named prop:

o = new Object();
o.hasOwnProperty('prop');   // returns false
o.prop = 'exists';
o.hasOwnProperty('prop');   // returns true

Direct vs. inherited properties

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

o = new Object();
o.prop = 'exists';
o.hasOwnProperty('prop');             // returns true
o.hasOwnProperty('toString');         // returns false
o.hasOwnProperty('hasOwnProperty');   // returns false

Iterating over the properties of an object

The following example shows how to iterate over the properties of an object without executing on inherited properties. Note that the for...in loop is already only iterating enumerable items, so one should not assume based on the lack of non-enumerable properties shown in the loop that hasOwnProperty itself is confined strictly to enumerable items (as with Object.getOwnPropertyNames()).

var buz = {
  fog: 'stack'
};

for (var 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
  }
}

Using hasOwnProperty as a property name

JavaScript does not protect the property name hasOwnProperty; thus, if the possibility exists that an object might have a property with this name, it is necessary to use an external hasOwnProperty to get correct results:

var foo = {
  hasOwnProperty: function() {
    return false;
  },
  bar: 'Here be dragons'
};

foo.hasOwnProperty('bar'); // always returns false

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

// It's also possible to use the hasOwnProperty property
// from the Object prototype for this purpose
Object.prototype.hasOwnProperty.call(foo, 'bar'); // true

Note that in the last case there are no newly created objects.

Specifications

Specification
ECMAScript (ECMA-262)
The definition of 'Object.prototype.hasOwnProperty' in that specification.

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:94 次

字数:8941

最后编辑:6 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文