如何检查ECMAScript 6类和函数之间的区别? [英] How do you check the difference between an ECMAScript 6 class and function?

查看:124
本文介绍了如何检查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));
}

这篇关于如何检查ECMAScript 6类和函数之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆