I read that we should always use hasOwnProperty when looping an object, because the object can be modified by something else to include some keys we don't want.
But is this always required? Are there situations where it's not needed? Is this required for local variables too?
function my(){ var obj = { ... }; for(var key in obj){ if(obj.hasOwnProperty(key)){ safe } } }
I just don't like adding an extra if inside the loop if I don't have to.
Death to hasOwnProperty
This guy says I shouldn't use it at all any more.
Then no, you don't need to use the hasOwnProperty() . But the full control over the environment is not something you should count on. It's fine to drop the hasOwnProperty() only until someone somewhere redefines the Object type. Before or even after your script is started.
The appropriate/recommended way to use hasOwnProperty is as a filter, or a means to determine whether an object... well, has that property. Just they way you are using it in your second command a. hasOwnProperty('abc') .
The hasOwnProperty() method returns true if the property is directly present in the object (not in its prototype chain). If an object is an Array, then the hasOwnProperty() method can check if an index is available (not empty) in the array.
hasOwnProperty() should be O(1) , as it is a key lookup, but it will be implementation specific.
Object.hasOwnProperty
determines if the whole property is defined in the object itself or in the prototype chain.
In other words: do the so-called check if you want properties (either with data or functions) coming from no other place than the object itself.
For example:
function A() { this.x = "I'm an own property"; } A.prototype.y = "I'm not an own property"; var instance = new A(); var xIsOwnProperty = instance.hasOwnProperty("x"); // true var yIsOwnProperty = instance.hasOwnProperty("y"); // false
Since ECMAScript 5.x, Object
has a new function Object.keys
which returns an array of strings where its items are the own properties from a given object:
var instance = new A(); // This won't contain "y" since it's in the prototype, so // it's not an "own object property" var ownPropertyNames = Object.keys(instance);
Also, since ECMAScript 5.x, Array.prototype
has Array.prototype.forEach
which let’s perform a for-each loop fluently:
Object.keys(instance).forEach(function(ownPropertyName) { // This function will be called for each found "own property", and // you don't need to do the instance.hasOwnProperty check any more });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With