HasOwnProperty is a method of Object.prototype that determines whether an Object contains custom properties and not properties on the prototype chain. HasOwnProperty is the only function in JavaScript that handles properties without looking up the prototype chain


Object.prototype.chang = 1; 
var foo = {goo: undefined};   / / object
foo.chang;                    / / 1
'bar' in foo;                 // true
foo.hasOwnProperty('chang');  // False chang is prototyped
foo.hasOwnProperty('goo');    // true
// In JS only the hasOwnProperty method can be used to exclude properties on the prototype chain, not properties defined on the object itself.
Copy the code

JavaScript does not protect hasOwnProperty from unauthorized possession, so if an object happens to have this property, you need to use an external hasOwnProperty function to get the correct result

var foo = {
    hasOwnProperty: function() {    // It already exists
        return false;
    },
    chang: 'Acquisition of Tencent'
};
foo.hasOwnProperty('chang'); // Always return false
// Use the hasOwnProperty of the {} object and set it above and below to foo
{}.hasOwnProperty.call(foo, 'chang'); // true
Copy the code

HasOwnProperty is the only method available when checking for the presence of a property on an object. It is also recommended to always use the hasOwnProperty method when iterating through objects using the For in Loop method. This will avoid the interference of prototype object extensions

Object.prototype.chang = 1;
var foo = {oo: 2};
for(var i in foo) {        / / for... The IN loop iterates not only over numeric key names, but also over values on the prototype and other manually added keys
    console.log(i);        // Outputs two attributes: chang and oo
}
                           // There is no way to change the behavior of the for in statement, so the only way to filter results is to use the hasOwnProperty method
                           // Modify the code as follows
for(var i in foo) {
    if (foo.hasOwnProperty(i)) { // Check to remove the prototype
        console.log(i); }}// hasOwnProperty is used, so only oo is output this time.
  // If you do not use hasOwnProperty, this code may fail when native Object prototypes (such as Object.prototype) are extended
  // Note that it is not enough to judge whether an attribute exists because I therefore pay because the value is set to undefined
Copy the code

If there is a mistake or not rigorous place, please leave a comment, very grateful, to the author is also a kind of encouragement.