Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

There are a lot of blogs saying that a hasOwnProperty check should be used whenever the for..in loop is used, but I don't understand why that's the case. Both with and without the check we get the same results.

Check out this fiddle.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
255 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you're creating a basic object with {}, or getting it from JSON using JSON.parse, then hasOwnProperty is globally useless.

But if you're extending a "class" (using prototype), then it helps you to know if you're accessing your "own properties" (direct properties, including direct functions).

Note that a basic object has at least one (not direct) property, that you may discover with console.log({}); or console.log({}.toString) but it's not enumerable and not seen in a for... in loop :

A for...in loop does not iterate over non–enumerable properties. Objects created from built–in constructors like Array and Object have inherited non–enumerable properties from Object.prototype and String.prototype that are not enumerable, such as String's indexOf method or Object's toString method. The loop will iterate over all enumerable properties of the object or that it inherits from its constructor's prototype (including any which overwrite built-in properties).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...