We all know that for...in loop is used to iterate over enumerable properties of object as well as properties of its prototypes, but what if we want to iterate over properties attached to the object itself, and not its prototypes.
this is where hasOwnProperty() method plays its role...eg shown below -:
var square = {a:1, b:2, c:3};
function ColoredSquare() {
this.color = "red";
}
ColoredSquare.prototype = square;
var obj = new ColoredSquare();
console.log(obj) // you can see object contains all the properties...
for (var prop in obj) {
if( obj.hasOwnProperty( prop ) ) { // condition to filter its own properites...
console.log("obj." + prop + " = " + obj[prop]);
}
}
// Output:
// Object { color="red", a=1, b=2, c=3}
// "obj.color = red"
In above example you can see that 'hasOwnProperty()' method will check whether it is objects own property or not and if it is, then methods will return 'true' otherwise 'false'...
1 Comment(s)