Skip to content

Instantly share code, notes, and snippets.

@edysegura
Created May 31, 2016 03:15
Show Gist options
  • Save edysegura/17630491e42539d4c9b078cfe01bf85f to your computer and use it in GitHub Desktop.
Save edysegura/17630491e42539d4c9b078cfe01bf85f to your computer and use it in GitHub Desktop.
[JS] Why to use hasOwnProperty?
// Poisoning Object.prototype
Object.prototype.bar = 1;
var foo = {goo: undefined};
console.log(foo.bar); // 1
console.log('bar' in foo); // true
console.log(foo.hasOwnProperty('bar')); // false
console.log(foo.hasOwnProperty('goo')); // true
//not safe without hasOwnProperty
for(var index in foo) console.log(index, foo[index]);
//safe
console.log(Object.keys(foo));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment