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

后端 未结 2 1224
一整个雨季
一整个雨季 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: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 

提交回复
热议问题