简体   繁体   中英

Is there a benefit to use “hasOwnProperty()” when iterating through object keys in JavaScript

I'm trying to understand the goal of using hasOwnProperty() check when iterating through object keys. As I know, the iteration will be executed for every object property (not more, not less) in both cases: with hasOwnProperty() or without. For example, in code below results with hasOwnProperty() check and without are the same:

 const obj = { prop1: [], prop2: {}, prop3: "", prop4: 0, prop5: null, prop6: undefined } const resultWithHasOwnProperty = []; const resultWithoutHasOwnProperty = []; for(key in obj) { if(obj.hasOwnProperty(key)) { resultWithHasOwnProperty.push(obj[key]) } } for(key in obj) { resultWithoutHasOwnProperty.push(obj[key]) } console.log("Result WITH hasOwnProperty check: ", resultWithHasOwnProperty); console.log("Result WITHOUT hasOwnProperty check: ", resultWithoutHasOwnProperty); 

So my question is: why and when should we use hasOwnProperty() check?

I'll rephrase my question: without hasOwnProperty() check we will always iterate through all existing properties anyway?

Notice, this question is not really a duplicate.

The docs indicate that:

The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as own (not inherited) property.

The hasOwnProperty method ensure that the property you are checking is directly on an instance of an object but not inherited from its prototype chain. If you don't check, it will loop through every property on the prototype chain.

const obj = {
  prop1: [],
  prop2: {},
  prop3: "",
  prop4: 0,
  prop5: null,
  prop6: undefined
}

obj.prototype = {foo: 'bar'};

P/s: NOTE that:

JavaScript does not protect the property name hasOwnProperty ; thus, if the possibility exists that an object might have a property with this name, it is necessary to use an external hasOwnProperty to get correct results:

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

foo.hasOwnProperty('bar'); // always returns false

So you need to use:

Object.prototype.hasOwnProperty.call(foo, 'bar');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM