Langdon wrote:

Something that simply wraps this all-to-common code:

var key;

for (key in obj) {
   if (obj.hasOwnProperty(key) === true) {
     ...
   }
}

Imo the problem is not that there is no wrapper method for this pattern, but that this code is all too common. It should rarely be needed, and is mostly wrong anyway.

The cases to consider are

* You use `obj` as a dictionary. If you want to safeguard against inherited properties, you use `obj = Object.create(null)`. Those objects don't even have a `.hasOwnProperty` method.
And with ES6, a `Map` is a better solution anyway.

* You are enumerating array keys. To safeguard against inherited properties from `Array.prototype`, you should not use `hasOwnProperty` but rather use the proper loop type that iterates indices instead.

* You are processing JSON. `JSON.parse`'d objects inherit only from `Object.prototype` which does not have enumerable properties anyway.

* You are processing (JSON/dictionary) objects and fear that someone added enumerable properties to `Object.prototype`. Well, that's their fault, not your loop's one. If the environment is broken, your code is as well; there's nothing you can - and need - to do against.

* You are processing arbitrary objects with unknown prototype chains. To skip inherited properties in a `for in` loop, the only safe approach is to use `if (Object.prototype.hasOwnProperty.call(obj, key))` or avoid the drama altogether via `Object.keys`/`Object.getOwnProperty…`.

The last case is the only one where you'd really need `hasOwnProperty`.
The proliferation of `if (obj.hasOwnProperty(key))` needs to be stopped, it's cargo cult programming at best.

Regards,
 Bergi
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to