hasOwnProperty vs propertyIsEnumerable

后端 未结 4 1111
执念已碎
执念已碎 2020-12-29 05:52

Can anyone enlighten me, what is the difference between hasOwnProperty and propertyIsEnumerable:

4条回答
  •  温柔的废话
    2020-12-29 06:23

    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.

提交回复
热议问题