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).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…