hasOwnProperty vs propertyIsEnumerable
The "propertyIsEnumerable" function always excludes properties that would not return true
for "hasOwnProperty". You've done nothing to make any properties not be enumerable, so in your test the results are the same.
You can use "defineProperty" to define properties that are not enumerable; see this reference at MDN.
Object.defineProperty(obj, "hideMe", { value: null, enumerable: false });
That's like:
obj.hideMe = null;
except the property won't show up in for ... in
loops, and tests with propertyIsEnumerable
will return false
.
This whole topic is about features not available in old browsers, if that's not obvious.
hasOwnProperty
will return true
even for non-enumerable "own" properties (like length
in an Array
). propertyIsEnumerable
will return true
only for enumerable "own" properties. (An "enumerable" property is a property that shows up in for..in
loops and such.)
Example:
var a = [];
console.log(a.hasOwnProperty('length')); // "true"
console.log(a.propertyIsEnumerable('length')); // "false"
Or with a non-array object:
var o = {};
Object.defineProperty(o, "foo", { enumerable: false });
console.log(o.hasOwnProperty('foo')); // "true"
console.log(o.propertyIsEnumerable('foo')); // "false"
(When you use Object.defineProperty
, enumerable
defaults to false
, but I've been explicit above for clarity.)