-
Using hasOwnProperty() method in "for...in" loop JS
about 9 years ago
-
almost 9 years ago
extremely helpful blog thanx nagender keep posting your blogs they are very helpful for the ROR community
-
about 9 years ago
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"
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'...
almost 9 years ago
extremely helpful blog thanx nagender keep posting your blogs they are very helpful for the ROR community
Can you help out the community by solving one of the following Javascript problems?
Do activity (Answer, Blog) > Earn Rep Points > Improve Rank > Get more opportunities to work and get paid!
For more topics, questions and answers, please visit the Tech Q&A page.
1 Comment(s)