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

后端 未结 2 1137
一整个雨季
一整个雨季 2020-12-17 10:31

I would like to know if there is a way to differentiate a JavaScript script function (function(){}) from a JavaScript native function (like Math.cos

相关标签:
2条回答
  • 2020-12-17 11:11

    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.

    0 讨论(0)
  • 2020-12-17 11:18

    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));          // true
    console.log(isNativeFn(customFn));          // false
    console.log(isNativeFn(customFn.bind({}))); // true, because bind 

    0 讨论(0)
提交回复
热议问题