Skip to content

Instantly share code, notes, and snippets.

@wizard04wsu
Created February 5, 2014 21:13
Show Gist options
  • Save wizard04wsu/8833223 to your computer and use it in GitHub Desktop.
Save wizard04wsu/8833223 to your computer and use it in GitHub Desktop.
Cross-browser Object.keys()
//returns an array of the properties & methods that are direct properties of an object (i.e., those that have not been inherited)
//see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
if(!Object.keys){
Object.keys = (function (){
"use strict";
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !({toString: null}).propertyIsEnumerable("toString"),
dontEnums = ["toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "constructor"];
return function keys(obj){
var i, prop, result = [];
if(obj === null || (typeof obj !== "object" && typeof obj !== "function")){
throw new TypeError("Object.keys called on non-object");
}
for(prop in obj){
if(hasOwnProperty.call(obj, prop)){
result.push(prop);
}
}
if(hasDontEnumBug){
for(i=0; i<dontEnums.length; i++){
if(hasOwnProperty.call(obj, dontEnums[i])){
result.push(dontEnums[i]);
}
}
}
return result;
};
})();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment