Skip to content

Instantly share code, notes, and snippets.

@FGasper
Created November 9, 2011 14:13
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 FGasper/1351541 to your computer and use it in GitHub Desktop.
Save FGasper/1351541 to your computer and use it in GitHub Desktop.
Object.gave, an improvement on hasOwnProperty() checks in for..in loops
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