在ECMAScript 6中,根据规范,class的typeof 类型是“function”。
但是,根据规范,不允许将通过class类语法创建的对象作为普通函数调用。换句话说,您必须使用new关键字,否则会引发TypeError。
TypeError: Classes can’t be function-called
因此,如果不使用try-catch(这种非常难看并破坏性能)方法下,如何检查function是来自类语法还是函数语法?
最简单方法是.toString()方法。
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));
}