Attributes of hasOwnProperty in js and Detailed Explanation of Example Usage

  • 2021-12-04 09:16:33
  • OfStack

1. js does not protect hasOwnProperty from illegal occupation. If this attribute happens to exist in an object, you need to use an external hasOwnProperty function to get the correct result.

2. hasOwnProperty is the only method available when checking whether an attribute exists on an object.

Instances


var foo = {
    hasOwnProperty: function() {
        return false;
    },
    bar: 'Here be dragons'
};
foo.hasOwnProperty('bar'); //  Always return  false
//  Object that uses other objects  hasOwnProperty And set its context to foo
({}).hasOwnProperty.call(foo, 'bar'); // true

Extension of knowledge points:

Judge whether its own attributes exist or not


var o = new Object();
o.prop = 'exists';

function changeO() {
 o.newprop = o.prop;
 delete o.prop;
}

o.hasOwnProperty('prop'); // true
changeO();
o.hasOwnProperty('prop'); // false

Judge self-attribute and inheritance attribute


function foo() {
 this.name = 'foo'
 this.sayHi = function () {
  console.log('Say Hi')
 }
}

foo.prototype.sayGoodBy = function () {
 console.log('Say Good By')
}

let myPro = new foo()

console.log(myPro.name) // foo
console.log(myPro.hasOwnProperty('name')) // true
console.log(myPro.hasOwnProperty('toString')) // false
console.log(myPro.hasOwnProperty('hasOwnProperty')) // fasle
console.log(myPro.hasOwnProperty('sayHi')) // true
console.log(myPro.hasOwnProperty('sayGoodBy')) // false
console.log('sayGoodBy' in myPro) // true

Traverse through all its own properties of 1 object

In the process of looking at open source projects, we often see source code similar to the following. for... in loop object, and then use the hasOwnProperty () method to ignore the inherited properties.


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
  }
}

Note hasOwnProperty as the attribute name

JavaScript does not protect the hasOwnProperty property name, so it may exist in an object containing this property name, and it is necessary to use an extensible hasOwnProperty method to get the correct result:


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

foo.hasOwnProperty('bar'); //  Always return  false

//  If you are worried about this situation, you can directly use the real  hasOwnProperty  Method 
//  Use another 1 Object of `hasOwnProperty`  And call
({}).hasOwnProperty.call(foo, 'bar'); // true

//  You can also use the  Object  Prototypic  hasOwnProperty  Attribute 
Object.prototype.hasOwnProperty.call(foo, 'bar'); // true


Related articles: