0

Now that classes are in ES6+, I'd like to be able to check if a value is a regular function or a class definition, something like:

console.log(isClass(class A {}), 'should be true')
console.log(isClass(class B {}), 'should be true')
console.log(isClass(function () {}), 'should be false')

However, I can't seem to find any ways of figuring this out. I've thought of using Object.getOwnPropertyNames(class A {}) as well as (class A {}).__proto__ === Function.prototype however they return true for functions as well.

So far the best I've come up with is:

function isClass (thing) {
    return typeof thing === 'function' && Object.getOwnPropertyNames(thing).indexOf('arguments') === -1
}

But that doesn't seem that robust.

balupton
  • 47,113
  • 32
  • 131
  • 182
  • 5
    possible duplicate http://stackoverflow.com/questions/30758961/how-to-check-if-a-variable-is-an-es6-class-declaration or this: http://stackoverflow.com/questions/29093396/how-do-you-check-the-difference-between-an-ecmascript-6-class-and-function – Georgette Pincin Aug 26 '15 at 19:50
  • thanks, duplicate of the second – balupton Aug 26 '15 at 19:55

1 Answers1

1

Looking at the compiled code generated by Babel, I think there is no way you can tell if a function is used as a class. Back in the time, JavaScript didn't have classes, and every constructor was just a function. Today's JavaScript class keyword don't introduce a new concept of 'classes', it's rather a syntax sugar.

ES6 code:

// ES6
class A{}

ES5 generated by Babel:

// ES5
"use strict";

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var A = function A() {
    _classCallCheck(this, A);
};

Of course, if you are into coding conventions, you could parse the function (the class), and check if it's name starts with a capital letter.

function isClass(fn) {
    return typeof fn === 'function' && /^(class|function [A-Z])/.test(fn);
}

EDIT:

Browsers which already support the class keyword can use it when parsing. Otherwise, you are stuck with the capital letter one.

Tamas Hegedus
  • 28,755
  • 12
  • 63
  • 97
  • That's pretty nifty, turns out my question is a duplicate of http://stackoverflow.com/q/29093396/130638 would be cool to see your answer over there too. – balupton Aug 26 '15 at 20:03