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
hasOwnProperty
expects the property name as a string.
When you call Test.hasOwnProperty(name)
you are passing it the value of the name variable (which doesn't exist), just as it would if you wrote alert(name).
Every object descended from Object inherits the hasOwnProperty
method. This method can be used to determine whether an object has the specified property as a direct property of that object;
When you're using for (var key in obj)
it will loop through the given object + its parent objects' properties on the prototype chain until it reaches the end of the chain. As you want to check only a specific object's properties, you need to use hasOwnProperty
.
This is not needed in for (var i = 0; i < length; i++)
or data.forEach()
.
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
});