Typescript/Angular/ES6: can I finally let `hasOwnProperty()` die in for loops?

前端 未结 1 1758
轮回少年
轮回少年 2020-11-28 16:17

I\'ve always disliked the need to check hasOwnProperty() when looping over objects in javascript:

for ( var key in object ) {
    if ( !object.h         


        
相关标签:
1条回答
  • 2020-11-28 16:48

    There's absolutely no reason to include this check when enumerating plain objects and others that you know have no enumerable inherited properties. You are right, no reasonable modern framework does this to Object.prototype.

    The death of hasOwnProperty checks has been proclaimed since 2012 :-)

    Am I only at risk of problems caused by my own team accidentally modifying prototypes (or accidentally importing libraries that modify prototypes)?

    Yes. Though the fix for such problems is not to modify prototypes (or to make the property non-enumerable), not to add hasOwnProperty checks everywhere.

    Or is there more room for trouble that I'm not aware of?

    No.

    Actually, omitting the if (!object.hasOwnProperty(key)) check might even solve some problems and avoid trouble. Not all objects you might want to enumerate are guaranteed to have a hasOwnProperty method, or one that does what you expect. The proper way to check - in cases where it is necessary - has always been with call:

    if (!Object.prototype.hasOwnProperty.call(object, key))
    

    (though of course there still are edge cases, but they don't depend on object)

    0 讨论(0)
提交回复
热议问题