Created
May 5, 2013 14:43
-
-
Save jpoehls/5521004 to your computer and use it in GitHub Desktop.
hasOwnProperty() example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function rightWay(obj) { | |
for (var key in obj) { | |
// Ignore properties that are inherited. | |
if (!obj.hasOwnProperty(key)) { | |
continue; | |
} | |
console.log(key); | |
} | |
} | |
function wrongWay(obj) { | |
for (var key in obj) { | |
console.log(key); | |
} | |
} | |
// You start out with code like this. | |
var obj = {}; | |
obj.x = 1; | |
obj.y = 2; | |
wrongWay(obj); | |
// .. which logs `x` and `y`. | |
// Then one day you use a new library that extends | |
// a base prototype without making the new property non-enumerable. | |
Object.prototype.answer = 42; | |
// Suddenly your code breaks because it is including the new property | |
// that it didn't expect. | |
wrongWay(obj); | |
// .. now logs `x`, `y`, and `answer` (from the prototype). | |
// You could have protected yourself by using | |
// `hasOwnProperty()` to ensure you only iterated | |
// over the properties on the object itself. | |
rightWay(obj); | |
// .. logs `x` and `y`, ignoring `answer` because it is on the prototype. | |
// Also the library author could have made `answer` non-enumerable | |
// to help avoid this problem but using `hasOwnProperty()` | |
// is still best-practice unless you /want/ to include | |
// the prototype's properties, of course. |
This is awesome explanation. To the point. Thanks 👍
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks for the simple explanation