在 ECMAScript 6 中,根据规范,类的 typeof
是 'function'
。
然而,根据规范,您也不允许将通过类语法创建的对象作为普通函数调用来调用。换句话说,您必须使用 new
关键字,否则会抛出 TypeError。
TypeError: 类不能被函数调用
所以如果不使用 try catch,这会非常丑陋并破坏性能,您如何检查一个函数是来自 class
语法还是来自 function
语法?
最佳答案
我认为检查函数是否为 ES6 类的最简单方法是检查 .toString()
的结果方法。根据es2015 spec :
The string representation must have the syntax of a FunctionDeclaration FunctionExpression, GeneratorDeclaration, GeneratorExpression, ClassDeclaration, ClassExpression, ArrowFunction, MethodDefinition, or GeneratorMethod depending upon the actual characteristics of the object
所以检查函数看起来很简单:
function isClass(func) {
return typeof func === 'function'
&& /^class\s/.test(Function.prototype.toString.call(func));
}
关于javascript - 你如何检查 ECMAScript 6 类和函数之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29093396/