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


in ecmascript 6 typeof of classes is, according specification, 'function'.

however according specification not allowed call object created via class syntax normal function call. in other words, must use new keyword otherwise typeerror thrown.

typeerror: classes can’t function-called

so without using try catch, ugly , destroy performance, how can check see if function came class syntax or function syntax?

i think simplest way check if function es6 class check result of .tostring() method. according es2015 spec:

the string representation must have syntax of functiondeclaration functionexpression, generatordeclaration, generatorexpression, classdeclaration, classexpression, arrowfunction, methoddefinition, or generatormethod depending upon actual characteristics of object

so check function looks pretty simple:

function isclass(func) {   return typeof func === 'function'      && /^class\s/.test(function.prototype.tostring.call(func)); } 

Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

gradle error "Cannot convert the provided notation to a File or URI" -

python - NameError: name 'subprocess' is not defined -