Hasownproperty Vs Propertyisenumerable
Solution 1:
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.
Solution 2:
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.)
Solution 3:
Simply stated:
hasOwnProperty
will return true if and only if the property is the property of the object and is not inherited. This one is simple.
and
propertyIsEnumerable
will return true if and only ifhasOwnProperty
returns true and the property is enumerable. SopropertyIsEnumerable
is one "additional requirement" on top of thehasOwnProperty
test, and the namepropertyIsEnumerable
would be more accurate if it ishasOwnPropertyAndIsEnumerable
.
Solution 4:
The difference is that propertyIsEnumerable returns true only if the property exists and if it possible to do ForIn on the property, hasOwnProperty will return true if the property exists regardless to ForIn support
From MSDN:
The propertyIsEnumerable method returns true if proName exists in object and can be enumerated using a ForIn loop. The propertyIsEnumerable method returns false if object does not have a property of the specified name or if the specified property is not enumerable. Typically, predefined properties are not enumerable while user-defined properties are always enumerable.
The hasOwnProperty method returns true if object has a property of the specified name, false if it does not. This method does not check if the property exists in the object's prototype chain; the property must be a member of the object itself.
Post a Comment for "Hasownproperty Vs Propertyisenumerable"