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

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

javascript - Should hasOwnProperty still be used with for..in statements

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

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

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...