Moncader Moncader - 1 year ago 87
Javascript Question

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

In ECMAScript 6 the

of classes is, according to the specification,

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
keyword otherwise a TypeError is thrown.

TypeError: Classes can’t be function-called

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
syntax or from the

Answer Source

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(;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download