如何确定一个JavaScript函数是本地的(没有testing'')

我想知道是否有一种方法可以区分JavaScript脚本函数( function(){} )和JavaScript本地函数(如Math.cos )。
我已经知道了func.toString().indexOf('[native code]') != -1技巧,但我想知道是否有另一种方法来检测它。

背景:
我需要创build一个No-op转发ES6代理,它可以处理对象上的本机函数,但是它会因TypeError: Illegal invocation (请参阅使用ES6代理和node.js的非法调用错误 )而失败。

为了解决这个问题,我在我的代理服务器的get处理程序中.bind()所有的函数,但是如果我能够有效地检测本机函数,我只需要.bind()这些原生函数。

更多细节: https : //github.com/FranckFreiburger/module-invalidate/blob/master/index.js#L106

注意:

 (function() {}).toString() -> "function () {}" (function() {}).prototype -> {} (require('os').cpus).toString() -> "function getCPUs() { [native code] }" (require('os').cpus).prototype -> getCPUs {} (Math.cos).toString() -> "function cos() { [native code] }" (Math.cos).prototype -> undefined (Promise.resolve().then).toString() -> "function then() { [native code] }" (Promise.resolve().then).prototype -> undefined 

编辑:
目前,最好的解决scheme是testing!('prototype' in fun)但它不会与require('os').cpus

您可以try使用Function构造函数与FunctiontoString值。 如果它不抛出错误,那么你得到一个自定义函数,否则你有一个本地函数。

 function isNativeFn(fn) { try { void new Function(fn.toString()); } catch (e) { return true; } return false; } function customFn() { var foo; } console.log(isNativeFn(Math.cos)); // true console.log(isNativeFn(customFn)); // false console.log(isNativeFn(customFn.bind({}))); // true, because bind 

我对这个主题的总结:不要使用它,这是行不通的。 你不能检测到一个函数是本地的,因为Function#bind()也会创build“本地”函数。

 function isSupposedlyNative(fn){ return (/\{\s*\[native code\]\s*\}/).test(fn); } function foo(){ } var whatever = {}; console.log("Math.cos():", isSupposedlyNative( Math.cos )); console.log("foo():", isSupposedlyNative( foo )); console.log("foo.bind():", isSupposedlyNative( foo.bind(whatever) ));