Skip to content

Instantly share code, notes, and snippets.

@rkatic
Created June 3, 2011 10:25
Show Gist options
  • Save rkatic/1006145 to your computer and use it in GitHub Desktop.
Save rkatic/1006145 to your computer and use it in GitHub Desktop.
A robust isNativeObject()
var isNativeObject = (function( window ){
var a = "Boolean Number String Function Array Date RegExp Object".split(" "),
natives = {},
hostTypes = {
"object": 1,
"function": 1
},
toStr = natives.toString,
slice = a.slice,
sliceTest = function( obj ) {
try {
slice.call( obj );
return 0;
} catch (e) {
return 1;
}
};
while ( a[0] ) {
natives[ "[object " + a.pop() + "]" ] = 1;
};
if ( sliceTest(window) ) {
sliceTest = 0;
}
return function( obj ) {
return obj != null && toStr.call( obj ) in natives &&
// Additional checks for IE6, IE7, IE8.
( !sliceTest || !hostTypes[ typeof obj ] || "hasOwnProperty" in obj && !( "length" in obj && sliceTest( obj ) ) );
};
})( this );
var isNativeObject=function(e){for(var c="Boolean Number String Function Array Date RegExp Object".split(" "),d={},f={object:1,"function":1},g=d.toString,h=c.slice,b=function(a){try{return h.call(a),0}catch(b){return 1}};c[0];)d["[object "+c.pop()+"]"]=1;b(e)&&(b=0);return function(a){return a!=null&&g.call(a)in d&&(!b||!f[typeof a]||"hasOwnProperty"in a&&!("length"in a&&b(a)))}}(this);
@rkatic
Copy link
Author

rkatic commented Jun 3, 2011

Tests.

Not supporting:

  • Host methods.
  • Special objects like window.location.
  • Math object.
  • Error instances.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment