Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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: 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 class syntax or from the function syntax?

like image 654
Moncader Avatar asked Mar 17 '15 07:03

Moncader


People also ask

What is the difference between class and function in JavaScript?

One key distinction between functions and classes was highlighted in this talk which suggests that a function is a behavior that can carry data while, inversely, a class is data that can carry behavior.

Do classes exist in JavaScript 6 ES6?

What are ES6 classes? In ES6, the "class" keyword and associated features are a new approach to creating prototype constructors. They are not true classes in a way that would be familiar to users of most other object-oriented languages.

Is an object or class or objects defined by ECMAScript?

A native object is an object or class of objects defined by the ECMAScript specification. Arrays, functions, dates, and regular expressions (for example) are native objects.


Video Answer


1 Answers

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)); } 
like image 194
alexpods Avatar answered Nov 04 '22 16:11

alexpods