如何检查ECMAScript 6类和函数之间的区别?
在ECMAScript 6中,类的 typeof
根据规范,'function'
。
In ECMAScript 6 the typeof
of classes is, according to the specification, 'function'
.
但是,根据规范,您不允许将通过类语法创建的对象调用为正常的函数调用。换句话说,您必须使用新的
关键字,否则将抛出TypeError。
However also according to the specification you are not allowed to call the object created via the class syntax as a normal function call. In other words, you must use the new
keyword otherwise a TypeError is thrown.
TypeError:类不能被函数调用
所以没有使用try catch,这将是非常丑陋和破坏性能,你怎么能检查一个函数是否来自类
语法或函数
语法?
So without using try catch, which would be very ugly and destroy performance, how can you check to see if a function came from the class
syntax or from the function
syntax?
我认为检查函数是否是ES6类的最简单的方法是检查 .toString()
方法。根据 es2015规格:
I think the simplest way to check if the function is ES6 class is to check the result of .toString()
method. According to the es2015 spec:
字符串表示必须具有FunctionDeclaration FunctionExpression,GeneratorDeclaration,GeneratorExpression,ClassDeclaration,ClassExpression,ArrowFunction,MethodDefinition或GeneratorMethod的语法,具体取决于实际对象的特征
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
所以检查功能看起来很简单:
So the check function looks pretty simple:
function isClass(func) {
return typeof func === 'function'
&& /^class\s/.test(Function.prototype.toString.call(func));
}