How to check if a variable is an ES6 class declaration?

后端 未结 4 2053
甜味超标
甜味超标 2020-12-11 00:09

I am exporting the following ES6 class from one module:

export class Thingy {
  hello() {
    console.log(\"A\");
  }

  world() {
    console.log(\"B\");
           


        
4条回答
  •  攒了一身酷
    2020-12-11 00:21

    If you want to ensure that the value is not only a function, but really a constructor function for a class, you can convert the function to a string and inspect its representation. The spec dictates the string representation of a class constructor.

    function isClass(v) {
      return typeof v === 'function' && /^\s*class\s+/.test(v.toString());
    }
    

    Another solution would be to try to call the value as a normal function. Class constructors are not callable as normal functions, but error messages probably vary between browsers:

    function isClass(v) {
      if (typeof v !== 'function') {
        return false;
      }
      try {
        v();
        return false;
      } catch(error) {
        if (/^Class constructor/.test(error.message)) {
          return true;
        }
        return false;
      }
    }
    

    The disadvantage is that invoking the function can have all kinds of unknown side effects...

提交回复
热议问题