发布网友
共4个回答
懂视网
The JavaScript
完成这个任务的方法非常简单:
function isNative(fn) { return (/{s*[native code]s*}/).test('' + fn); }
toString方法会返回这个方法的字符串形式,然后用正则表达式判断里面包含的字符。
更强悍的方法
Lodash的创始人John-David Dalton找到了一个更佳的方案:
;(function() { // Used to resolve the internal `[[Class]]` of values var toString = Object.prototype.toString; // Used to resolve the decompiled source of functions var fnToString = Function.prototype.toString; // Used to detect host constructors (Safari > 4; really typed array specific) var reHostCtor = /^[object .+?Constructor]$/; // Compile a regexp using a common native method as a template. // We chose `Object#toString` because there's a good chance it is not being mucked with. var reNative = RegExp('^' + // Coerce `Object#toString` to a string String(toString) // Escape any special regexp characters .replace(/[.*+?^${}()|[]/\]/g, '\$&') // Replace mentions of `toString` with `.*?` to keep the template generic. // Replace thing like `for ...` to support environments like Rhino which add extra info // such as method arity. .replace(/toString|(function).*?(?=\()| for .+?(?=\])/g, '$1.*?') + '$' ); function isNative(value) { var type = typeof value; return type == 'function' // Use `Function#toString` to bypass the value's own `toString` method // and avoid being faked out. ? reNative.test(fnToString.call(value)) // Fallback to a host object check because some environments will represent // things like typed arrays as DOM methods which may not conform to the // normal native pattern. : (value && type == 'object' && reHostCtor.test(toString.call(value))) || false; } // export however you want module.exports = isNative; }());
现在你也看到了,很复杂,但更强大。当然,这不是为了做安全防护,它只是给你提供是否是原生函数的相关信息。
热心网友
可以通过typeof进行判断是否为函数,typeof用法如下:
typeof 运算符有一个参数,即要检查的变量或值
对变量或值调用 typeof 运算符将返回下列值之一:
undefined - 如果变量是 Undefined 类型的
boolean - 如果变量是 Boolean 类型的
number - 如果变量是 Number 类型的
string - 如果变量是 String 类型的
object - 如果变量是一种引用类型或 Null 类型的
function - 如果变量代表一个函数
热心网友
function isFunction(obj){
return Object.prototype.toString.call(obj)==='[object Function]'
}
热心网友
var a = function(){};
var b = 'abc';
var c = 123;
function isFunc(test){
return typeof test == 'function';
}
isFunc(a);//true
isFunc(b);//false
isFunc(c);//false