-
-
Save localpcguy/b4d8f906e100a0430ef3c301da94f87f to your computer and use it in GitHub Desktop.
JavaScript: Object#forIn and Object#forOwn
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
/* | |
* 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