Created
November 9, 2011 14:13
-
-
Save FGasper/1351541 to your computer and use it in GitHub Desktop.
Object.gave, an improvement on hasOwnProperty() checks in for..in loops
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
var HOP = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty); | |
//Checks the prototype chain to see if the "giver" "gave" the "key" to the "obj". | |
Object.gave = function(giver,key,obj) { | |
//If there are 2 arguments instead of 3, use the Function.prototype method. | |
if (arguments.length === 2) { | |
Function.prototype.gave.apply(this,arguments); | |
} | |
var last_prototype; | |
while ( obj !== giver ) { | |
if (HOP(obj,key) || (obj === last_prototype)) return false; | |
last_prototype = obj; | |
obj = Object.getPrototypeOf(obj); | |
} | |
return true; | |
}; | |
//Like the above, but makes the Function prototype the "giver". | |
//This improves on hasOwnProperty() checks in for..in loops by allowing | |
//prototypal inheritance while still weeding out constructor prototypes. | |
//e.g.: for (key in obj) { if (!Object.gave(key,obj)) { ... } } | |
Function.prototype.gave = function(key,obj) { | |
return Object.gave( this.prototype, key, obj ); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment