Guide to using the hasOwnProperty of method in javascript

  • 2020-05-12 02:09:47
  • OfStack

An overview of the

The hasOwnProperty() method is used to determine whether an object has the specified properties of itself.

grammar
obj.hasOwnProperty(prop)

parameter

•prop

The & # 8226; The name of the property to be detected.

describe

All objects that inherit from Object.prototype will inherit from the prototype chain to the hasOwnProperty method. This method can be used to detect whether an object contains specific properties of itself. Unlike the in operator, this method will ignore properties inherited from the prototype chain.

The sample

Example 1: use the hasOwnProperty method to determine whether an object has specific properties of its own

The following example detects whether the object o has its own property prop:


o = new Object();o.prop = 'exists';function changeO() {
  o.newprop = o.prop;
  delete o.prop;}o.hasOwnProperty('prop');  
  // return true
  changeO();
   o.hasOwnProperty('prop'); 
   // return false

Example 2: the difference between an own property and an inherited property

The following example demonstrates the difference between the hasOwnProperty method treating its own properties and inherited properties:


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

Example 3: walk through all the properties of an object itself

The following example demonstrates how to ignore the inherited properties while walking through all the properties of an object, notice here for.. The in loop only traverses enumerable properties, which is usually what we want, and a similar requirement can be achieved directly using the Object.getOwnPropertyNames () method.


var buz = {
    fog: 'stack'};
    for (var name in buz) {
    if (buz.hasOwnProperty(name)) {
        alert("this is fog (" + name + ") for sure. Value: " + buz[name]);
    }
    else {
        alert(name);
         // toString or something else   
         }}

Example 4: the hasOwnProperty method may be obscured

If an object has its own hasOwnProperty method, the method of the same name on the prototype chain is obscured (shadowed) :


var foo = {
    hasOwnProperty: function() {
        return false;
    },
    bar: 'Here be dragons'};foo.hasOwnProperty('bar');
    // Always return false
    // If you're worried about this, you can just use the real thing on the prototype chain hasOwnProperty methods
    ({}).hasOwnProperty.call(foo, 'bar');
    // true
    Object.prototype.hasOwnProperty.call(foo, 'bar');
    // true

That's all for this article, I hope you enjoy it.


Related articles: