How to determine that a JavaScript function is native (without testing '[native code]') How to determine that a JavaScript function is native (without testing '[native code]') node.js node.js

How to determine that a JavaScript function is native (without testing '[native code]')


You could try to use a Function constructor with the toString value of the function. If it does not throw an error, then you get a custom function, otherwise you have a native function.

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


My summary on this topic: don't use it, it doesn't work. You can not certainly detect wether a function is native, because Function#bind() also creates "native" functions.

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) ));

And since the Version by John-David Dalton, which Tareq linked to in this comment, does basically the same that code doesn't work either. I've checked it.

And the approach from Nina works on a similar principle, because again it is the [native code] part in the function body wich throws the error when trying to parse it into a new function.

The only secure way to determine wether the function you're dealing with is the native function, is to hold a reference to the native function and compare your function against that reference, but I guess this is no option for your use case.