【JavaScript原生】Object.prototype.hasOwnProperty()

Object.prototype.hasOwnProperty()

The hasOwnProperty() method returns a boolean value indicating whether the object has the specified property (that is, whether it has the specified key) in its own properties. In layman's terms: it is used to determine whether a property is defined in the object itself rather than inherited from the prototype chain.

grammar

obj.hasOwnProperty(prop)

  • The String string representation of the name, or Symbol, of the property to check for prop .
  • Return value Boolean
    used to determine whether an object has the specified property.

example

const obj = {
    
    };
obj.property1 = 88;

console.log(obj.hasOwnProperty('property1'));  // true

console.log(obj.hasOwnProperty('toString'));  // false

console.log(obj.hasOwnProperty('hasOwnProperty')); // false

Note: Even if the property's value is nullor undefined, as long as the property exists, hasOwnPropertyit will still be returned true.

o = new Object();
o.lisi = null;
o.hasOwnProperty('lisi'); // 返回 true
o.lizi = undefined;
o.hasOwnProperty('lizi'); // 返回 true

Using the hasOwnProperty method to determine whether a property exists
The following example checks whether an object o has its own property prop:

o = new Object();
o.hasOwnProperty('prop'); // 返回 false
o.prop = 'exists';
o.hasOwnProperty('prop'); // 返回 true
delete o.prop;
o.hasOwnProperty('prop'); // 返回 false

Owned and Inherited Properties
The following example demonstrates the difference between the hasOwnProperty method's treatment of owned and inherited properties:

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

Using hasOwnProperty as the property name
JavaScript does not protect hasOwnPropertythe property name, so there is a situation where hasOwnProperty is set as the function name:

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

Then, when using:

foo.hasOwnProperty('bar'); // 始终返回 false

To solve this situation, you can use the following two methods:

// 1. 可以直接使用原型链上真正的 hasOwnProperty 方法
({
    
    }).hasOwnProperty.call(foo, 'bar'); // true

// 2. 使用 Object 原型上的 hasOwnProperty 属性
Object.prototype.hasOwnProperty.call(foo, 'bar'); // true

Notice, and only in the last case, no new object will be created.

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

Guess you like

Origin blog.csdn.net/weixin_43853746/article/details/121887963