您如何检查 ECMAScript 6 类和函数之间的区别? [英] How do you check the difference between an ECMAScript 6 class and function?
问题描述
在 ECMAScript 6 中,根据规范,类的 typeof
是 'function'
.
In ECMAScript 6 the typeof
of classes is, according to the specification, 'function'
.
但是,根据规范,您也不能像普通函数调用一样调用通过类语法创建的对象.换句话说,您必须使用 new
关键字,否则会抛出 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,这会非常丑陋并破坏性能,你如何检查一个函数是来自class
语法还是来自function
语法?
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 class 的最简单方法是检查 .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'
&& /^classs/.test(Function.prototype.toString.call(func));
}
这篇关于您如何检查 ECMAScript 6 类和函数之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!