andy-h
2/5/2014 - 3:18 PM

Cross-browser Object.getPrototypeOf()

Cross-browser Object.getPrototypeOf()

//add Object.getPrototypeOf() if it's not supported
//	- if the __proto__ property is not supported either, this may break if anything in the object's prototype chain has been tampered with
//	- see http://ejohn.org/blog/objectgetprototypeof/

(function (){
	"use strict";
	function isPrimitive(o){ var t; return o===t || o===null || (t = typeof o)==="number" || t==="string" || t==="boolean"; }
	if(!Object.getPrototypeOf){
		if(typeof("".__proto__) === "object"){
			Object.getPrototypeOf = function getPrototypeOf(object){
				if(isPrimitive(object)){
					throw new TypeError("first argument is not an object");
				}
				return object.__proto__;
			};
		}
		else{
			//this version may break if the prototype chain has been tampered with
			Object.getPrototypeOf = function getPrototypeOf(object){
				if(isPrimitive(object)){
					throw new TypeError("first argument is not an object");
				}
				//if(object === Object.prototype){	//doesn't work since `object` may be in a different window
				if(object === object.constructor.prototype){
					return null;
				}
				return object.constructor.prototype;
			};
		}
	}
})();