Use of hasOwnProperty Method of js Attribute Object

  • 2021-10-25 06:03:24
  • OfStack

The hasOwnProperty () method of Object returns a Boolean value to determine whether the object contains a specific self (non-inherited) property.

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

Reference link


Related articles: