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