Skip to content

Instantly share code, notes, and snippets.

@localpcguy
Forked from cowboy/object-forin-forown.js
Created February 27, 2017 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save localpcguy/b4d8f906e100a0430ef3c301da94f87f to your computer and use it in GitHub Desktop.
Save localpcguy/b4d8f906e100a0430ef3c301da94f87f to your computer and use it in GitHub Desktop.
JavaScript: Object#forIn and Object#forOwn
/*
* Object#forIn, Object#forOwn
*
* Copyright (c) 2012 "Cowboy" Ben Alman
* Licensed under the MIT license.
* http://benalman.com/about/license/
*/
Object.defineProperties(Object.prototype, {
forIn: {
writable: true,
configurable: true,
value: function(iterator, thisValue) {
for (var prop in this) {
iterator.call(thisValue, this[prop], prop, this);
}
}
},
forOwn: {
writable: true,
configurable: true,
value: function(iterator, thisValue) {
Object.keys(this).forEach(function(key) {
iterator.call(thisValue, this[key], key, this);
}, this);
}
}
});
var obj = {a: 1, b: 2};
var sub = Object.create(obj);
sub.c = 3;
sub.d = 4;
sub.forIn(console.log, console);
// 3 'c' { c: 3, d: 4 }
// 4 'd' { c: 3, d: 4 }
// 1 'a' { c: 3, d: 4 }
// 2 'b' { c: 3, d: 4 }
sub.forOwn(console.log, console);
// 3 'c' { c: 3, d: 4 }
// 4 'd' { c: 3, d: 4 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment