Created
June 13, 2011 14:39
-
-
Save xavierm02/1022883 to your computer and use it in GitHub Desktop.
Polyfill for Object.getPrototypeOf -- It will work unless your constructor's prototype doesn't have a constructor property (which means you assigned another object as prototype and didn't give it a constructor property...)
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
if ( typeof Object.getPrototypeOf !== "function" ) { | |
( function ( ) { | |
function getPrototypeValue( o, p ) { | |
if ( o.hasOwnProperty( p ) ) { | |
var ownValue = o[ p ]; | |
if ( delete o[ p ] ) { | |
var prototypeValue = o[ p ]; | |
o[ p ] = ownValue; | |
return prototypeValue; | |
} else { | |
return o[ p ]; | |
} | |
} else { | |
return o[ p ]; | |
} | |
} | |
if ( typeof "".__proto__ === "object" ) { | |
Object.getPrototypeOf = function( object ) { | |
return getPrototypeValue( object, '__proto__' ); | |
}; | |
} else { | |
Object.getPrototypeOf = function( object ) { | |
getPrototypeValue( object, 'constructor' ).prototype; | |
}; | |
} | |
}( ) ); | |
} |
What makes this work consistently is to enforce it with an Object.create polyfill that adds proto to all newly created objects when called, that way your else never gets used, but I suppose I am digressing...
When you say proto you mean proto ? Because there are some browser supproting proto and not Object.create. So it would create some weird bugs.
And if it is proto then you need to add an else if.
if you polyfill Object.create to add the proto then you won't hit the else above.
You'd still need it to work on objects created with the new operator.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It needs the constructor property to work properly.