Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.