Created
June 6, 2012 00:04
-
-
Save stoyan/2878985 to your computer and use it in GitHub Desktop.
version of Andrea's
This file contains 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
var isNativeFunction = function (f) { | |
try { | |
Function("return " + f.toString()); | |
return false; | |
} catch (_) { | |
return true; | |
} | |
}; |
// this will return true
isNativeFunction(function f(){
f.toString = function () {
return "function () {[native code]}";
};
return f;
}());
// this as well ...
isNativeFunction({});
so ... as summary, I would suggest this one
var isNativeFunction = function(Function){
var s, toString = Function.prototype.toString;
return function isNativeFunction(f) {
try {
// object.toString can be reassigned
// native toString from Function.prototype
// should be borrowed, sandboxed, to ensure
// that we are using the right function
// rather than one redefined by a user
s = toString.call(f);
try {
// native functions cannot
// be evaluated (as de facto rule)
Function("return " + s);
} catch(_) {
// if evaluation fails
// we can assume it's native
return true;
}
} catch(_) {
// if toString.call failed
// the object has no [[Call]] property
// then is not a function
}
// all cases except the first nested catch
return false;
};
}(Function);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
isNativeFunction([].map); // true
isNativeFunction(alert); // true
isNativeFunction(Array); // true
isNativeFunction(isNativeFunction); // false
isNativeFunction(function(){""}); // false
isNativeFunction(function(){}); // false
isNativeFunction(Function()); // false
isNativeFunction(new Function('a', 'return a')); // false