How do you check the difference between an ECMAScript 6 class and function?

前端 未结 8 1919
借酒劲吻你
借酒劲吻你 2020-12-07 19:19

In ECMAScript 6 the typeof of classes is, according to the specification, \'function\'.

However also according to the specification you are

8条回答
  •  天命终不由人
    2020-12-07 19:33

    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:

    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));
    }
    

提交回复
热议问题