Skip to content

Instantly share code, notes, and snippets.

@stoyan
Created June 6, 2012 00:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stoyan/2878985 to your computer and use it in GitHub Desktop.
Save stoyan/2878985 to your computer and use it in GitHub Desktop.
version of Andrea's
var isNativeFunction = function (f) {
try {
Function("return " + f.toString());
return false;
} catch (_) {
return true;
}
};
@stoyan
Copy link
Author

stoyan commented Jun 6, 2012

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

@WebReflection
Copy link

// this will return true
isNativeFunction(function f(){
  f.toString = function () {
    return "function () {[native code]}";
  };
  return f;
}());

// this as well ...
isNativeFunction({});

@WebReflection
Copy link

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