andy-h
2/5/2014 - 9:13 PM

Cross-browser Object.keys()

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;
		};
	})();
}