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

查看:20
本文介绍了您如何检查 ECMAScript 6 类和函数之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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屋!

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